Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.NET: Deserializing Nested Json

Tags:

json

json.net

How do I deserialize the "Items" class part on this Json string:

{
"Buddies": {
    "count": 1,
    "items": [
        {
            "id": "5099207ee4b0cfbb6a2bd4ec",
            "firstName": "Foo",
            "lastName": "Bar",
            "image": {
                  "url": "",
                    "sizes": [
                        60,
                        120,
                        180,
                        240,
                        360
                    ],
                    "name": "myphoto.png"
                }
            }
        ]
    }
}

The original class that I have is :

public class Buddy 
{
   public IEnumerable<Item> Items { get; set; }
   public class Item {
       public string Id { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
   }
}

But the upper part of json is pretty useless to me and I want to use this class instead:

public class Buddy 
{
       public string Id { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }       
}
like image 865
gnaungayan Avatar asked Nov 25 '12 12:11

gnaungayan


2 Answers

Here's an approach using JSONPath, assuming your JSON is in a variable named json:

var buddies = JObject.Parse(json).SelectToken("$.Buddies.items").ToObject<Buddy[]>();
like image 99
Zac Charles Avatar answered Oct 20 '22 13:10

Zac Charles


I'm not aware of out of the box solution if any, but what stops you from writing few lines of code similar to shown below, in order to build the new collection:

var obj = JsonConvert.DeserializeObject<dynamic>(jsonstring);
var items = new List<Buddy>();
foreach (var x in obj.Buddies.items)
{
    items.Add(new Buddy
                  {
                      Id = x.id,
                      FirstName = x.firstName,
                      LastName = x.lastName
                  });
}
like image 26
jwaliszko Avatar answered Oct 20 '22 14:10

jwaliszko