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; }
}
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[]>();
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
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With