Guchen Guchen - 1 year ago 115
C# Question

C# get children from JSON

my JSON looks like this:

{
"kind": "youtube#videoListResponse",
"etag": "\"sZ5p5Mo8dPpfIzLYQBF8QIQJym0/TOPzMxlQJUtRJBXHeKYMXsdEkHs\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"sZ5p5Mo8dPpfIzLYQBF8QIQJym0/BIVqr1Mkbule8othzWvZRor92wU\"",
"id": "QMNkWwq6L4Q",
"contentDetails": {
"duration": "PT4M45S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": true,
"projection": "rectangular"
}
}
]
}


The formatting might be a bit off, sorry.
I tried creating a class like this:

public class VideoDetails
{
public string kind;
public string etag;
public string id;
public string duration;
public string definition;
public string caption;
public string licensedContent;
public string projection;
}


After that I deserialize the JSON file:

VideoDetailRead = JsonConvert.DeserializeObject<VideoDetails>(json);


but I only get "etag" and "kind". Nothing else. My question is: How do I read the data that's listed under "items"? This is my first time working with JSON and therefor I don't know much. Thanks for some answers.

Answer Source

Create a second object to model the children data. Provided the items property has also a child under contentDetails, you will also need another object to deserialize these properties.

public class VideoDetailsItem
{
     public string kind;
     public string etag;
     public string id;
     public VideoContentDetails contentDetails;
}

public class VideoContentDetails
{
     public string duration;
     public string definition;
     public string caption;
     public bool licensedContent;
     public string projection;
}

And to the parent object add a List<VideoDetailsItem>.

public class VideoDetails
{
    public string kind;
    public string etag;
    public List<VideoDetailsItem> items;
}

When deserializing JSON objects you have to mimic the JSON object structure in your object. Also, consider using properties instead of public fields to favor encapsulation in your data objects.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download