Dawnkeeper Dawnkeeper - 1 month ago 17
JSON Question

JSon.NET deserialising subitems

For deserialisation I usually use an object with the same property names as found in the JSon and

JsonConvert.DeserializeObject<Des>(jsonstring)
.

But now I came across this:

{
"id": 0815,
"name": "whatever"
"addedInfo": {
"thisisinteresting": 4711,
"id_str": "2336"
}
}


How can I tell JSon.Net to pull the 'thisisinteresting' part of the sub category into a class like:

class Des
{
int id;
string name;
int thisisinteresting;
}

Answer

The trivial way would be to actually model your class to the JSON structure:

public class AddedInfo
{
    public int thisisinteresting { get; set; }
    public string id_str { get; set; }
}

public class RootObject
{
    public int id { get; set; }
    public string name { get; set; }
    public AddedInfo addedInfo { get; set; }
}

Then add a property to the RootObject to emit the property:

public class RootObject
{
    public int id { get; set; }
    public string name { get; set; }
    public AddedInfo addedInfo { get; set; }

    [JsonIgnore]
    public int thisisinteresting { get { return addedInfo.thisisinteresting; } }
}

There are alternatives like creating a custom serializer or using JObject and deserialize the structure yourself, but I won't go into that. If you need to parse the JSON anyway, the price to deserialize it entirely is small.

Comments