Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Json Serialized c#

Tags:

json

c#

mvvm

I am trying to get the id from this json text. I'm not sure how to go about getting it doesn't let me create a json object. I tried deserializing it doing this:

public async Task<List<T>> GetIdAsync(string username)
{
    var httpClient = new HttpClient();

    var json = await httpClient.GetStringAsync(WebServiceURL);

    var  Id  = JsonConvert.DeserializeObject<List<T>>(json);

   return Id;
}

but I get this error during the deserialization

Unhandled Exception:

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path '', line 1, position 2

this is the json text:

json    "[{\"Id\":1,\"FirstName\":\"a\",\"LastName\":\"b\",\"UserName\":\"user\",\"Email\":\"[email protected]\",\"Password\":\"poSsUrscOuXL+E5qxXsCsA==\",\"CompanyName\":\"c\",\"Salt\":\"n3ZLSwU9L1g=\",\"Address\":{\"Country\":\"c\",\"Province\":\"p\",\"City\":\"c\",\"PostalCode\":\"p\",\"Street\":\"street\",\"StreetNumber\":\"123\"},\"Telephone\":{\"PersonalPhoneNumber\":\"413414\",\"BusinessPhoneNumber\":\"134134\"},\"Location\":{\"Lat\":45.6025839,\"Lng\":-97.8489959}}]"   string
like image 678
JayPhillips Avatar asked Dec 08 '25 14:12

JayPhillips


1 Answers

Given value of provided JSON which is an array of objects. You can use dynamic object to extract just the property you want. First deserialize the json to a List<dynamic>, get the first object in the list and call the Id property.

public async Task<int> GetIdAsync(string username) {
    var httpClient = new HttpClient();

    var json = await httpClient.GetStringAsync(WebServiceURL);

    var list  = JsonConvert.DeserializeObject<List<dynamic>>(json);

    var obj = list.FirstOrDefault();

    int Id = obj != null ? obj.Id : 0;

    return Id;
}

UPDATE:

Tested it in a simple unit test and passes as expected.

[TestClass]
public class UnitTest6 {
    [TestMethod]
    public async Task GetIdAsyncTest() {

        var id = await GetIdAsync("");

        Assert.IsTrue(id > o);
    }

    public async Task<int> GetIdAsync(string username) {
        var httpClient = new HttpClient();
        //simple data just for the purpose of the test.
        var json = await Task.FromResult("[{\"Id\":1,\"FirstName\":\"a\"}]"); //await httpClient.GetStringAsync("");

        var list = JsonConvert.DeserializeObject<List<dynamic>>(json);

        var obj = list.FirstOrDefault();

        int Id = obj != null ? obj.Id : 0;

        return Id;
    }
}
like image 55
Nkosi Avatar answered Dec 11 '25 15:12

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!