JayPhillips JayPhillips - 8 days ago 6
JSON Question

Read Json Serialized c#

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\":\"d@gmail.com\",\"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

Answer

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;
    }
}
Comments