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; }       
}

4 Answers 4

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[]>();
Sign up to request clarification or add additional context in comments.

Comments

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
                  });
}

1 Comment

I like this approach, but wouldn't this be neet to put this in the Custom Converter logic?
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

Comments

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#

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.