Demarily Demarily - 6 months ago 14
JSON Question

How to deserialize an object with an object as it's value

I am in a pickle. I can not find how to deserialize this json. Everything i've found online talks about how to handle a key/value where the value is a type not an object. In this case the value is an object that has additional key/values inside.

Additionally, the long guid like string that you see there after "territories", is never the same...

How do i deserialize this with JSON.NET? I would love to be able to get the ID and the Name.

Thank you for reading this

{
"territories":{
"6368e494-c47c-4678-89de-45f3bfc35247":{
"id":"6368e494-c47c-4678-89de-45f3bfc35247",
"name":"Atlanta Camera Operations",
"center":[
33748995,
-84387983
],
"timeZoneCode":"America/New_York",
"languageCode":"en"
},
"4d998d4c-fcc6-4fdc-9e73-3f2e7515ee47":{
"id":"4d998d4c-fcc6-4fdc-9e73-3f2e7515ee47",
"name":"Atlanta Operations",
"center":[
33748995,
-84387983
],
"timeZoneCode":"America/New_York",
"languageCode":"en"
}
}
}

Answer

Here's a class that will hold the territory info:

class Territory
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("center")]
    public IList<int> Center { get; set; }

    [JsonProperty("timeZoneCode")]
    public string TimeZoneCode { get; set; }

    [JsonProperty("languageCode")]
    public string LanguageCode { get; set; }
}

Then you can deserialize them one by one like this:

string myJsonText = "your json here";

var jsonObject = JObject.Parse(myJsonText);
var territoriesToken = jsonObject["territories"];

We loop through the children and deserialize them:

var territoriesList = new List<Territory>();
foreach (var child in territoriesToken.Children())
{
    var territory = child.First.ToObject<Territory>();
    territoriesList.Add(territory);
}

Or if you prefer LINQ one liners you can use this:

var territoriesList = territoriesToken.Children()
                      .Select(child => child.First.ToObject<Territory>())
                      .ToList();

You can then access the name and id like you would with any other C# object

territoriesList[0].Id
territoriesList[0].Name
Comments