7

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; }       
}
gnaungayan
  • 522
  • 1
  • 9
  • 22

4 Answers4

9

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[]>();
Zac Charles
  • 1,208
  • 14
  • 19
4

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
                  });
}
jwaliszko
  • 16,942
  • 22
  • 92
  • 158
  • I like this approach, but wouldn't this be neet to put this in the Custom Converter logic? – keyr Nov 27 '12 at 13:28
0

Create a JsonConverter in which one can loop through the property and its value and create the desired object. For more informaiton see search in stackoverflow for JsonConverter e.g. http://stackoverflow.com/questions/2315570/json-net-how-to-serialize-a-class-using-custom-resolver. I also liked the approach of Jaroslaw

keyr
  • 990
  • 13
  • 27
0

You can use this code:

dynamic dictionary = 
(JsonConvert.DeserializeObject <IDictionary<string, object> > (jsonstring) )["Buddies"];

            var response = dictionary.items;

            foreach (var item in response)
            {

                var firstName= item.firstName;

            }

you can also see: Parsing a complex JSON result with C#

Community
  • 1
  • 1