crystyxn crystyxn - 1 month ago 7
C# Question

Retrieve the information from a nested JSON value

So I'm calling the LinkedIn API to get the profile data and it retrieves a JSON.

{
"firstName": "Cristian Viorel",
"headline": ".NET Developer",
"location": {
"country": {"code": "dk"},
"name": "Northern Region, Denmark"
},
"pictureUrls": {
"_total": 1,
"values": ["https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z..."]
}
}


I can use student.firstname, student.headline. How can I get the name of the location, or the value of the pictureUrl ?
Something like student.location.name or student.pictureUrls.values ?

Answer

Pretty easy with Json.Net. You first define your model:

public class Country
{
    public string code { get; set; }
}

public class Location
{
    public Country country { get; set; }
    public string name { get; set; }
}

public class PictureUrls
{
    public int _total { get; set; }
    public List<string> values { get; set; }
}

public class JsonResult
{
    public string firstName { get; set; }
    public string headline { get; set; }
    public Location location { get; set; }
    public PictureUrls pictureUrls { get; set; }
}

Then you simply parse your Json data:

string json = @"{
      'firstName': 'Cristian Viorel',
      'headline': '.NET Developer',
      'location': {
        'country': {'code': 'dk'},
        'name': 'Northern Region, Denmark'
      },
      'pictureUrls': {
        '_total': 1,
        'values': ['https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z...']
      }
    }";

JsonResult result = JsonConvert.DeserializeObject<JsonResult>(json);

Console.WriteLine(result.location.name);

foreach (var pictureUrl in result.pictureUrls.values)
    Console.WriteLine(pictureUrl);
Comments