Reputation: 1745
I have some JSON as shown below. I would like to get all objects from it where the "type" is "Item".
string json = @"
{
'name': 'Object 1',
'content': {
'body': {
'id': 'body',
'type': 'Body'
},
'style': {
'id': 'style',
'type': 'Style'
},
'DynamicName-123': {
'id': 'DynamicName-123',
'type': 'Row'
},
'DynamicName-434': {
'id': 'DynamicName-434',
'type': 'Column'
},
'DynamicName-223': {
'id': 'DynamicName-223',
'type': 'Item'
}
}
}";
JObject obj = JObject.Parse(json);
Expected output:
'id': 'DynamicName-223',
'type': 'Item'
How can I do this?
Upvotes: 1
Views: 6405
Reputation: 129777
You can get the objects that have a "type" property value of "Item" using a LINQ-to-JSON query like this:
JObject obj = JObject.Parse(json);
List<JObject> items = obj["content"]
.Children<JProperty>()
.Where(p => (string)p.Value["type"] == "Item")
.Select(p => (JObject)p.Value)
.ToList();
Fiddle: https://dotnetfiddle.net/dy1nQC
Upvotes: 6
Reputation: 7054
You can deserialize to anonymous type with Dictionary inside:
var template = new {name = "", content = new Dictionary<string, JObject>()};
var result = JsonConvert.DeserializeAnonymousType(json, template);
Now you can get all info from nested items:
foreach (var item in result.content)
Console.WriteLine($"{item.Key}: id = {item.Value["id"]}, type = {item.Value["type"]}");
Output will be:
body: id = body, type = Body
style: id = style, type = Style
DynamicName-123: id = DynamicName-123, type = Row
DynamicName-434: id = DynamicName-434, type = Column
DynamicName-223: id = DynamicName-223, type = Item
Upvotes: 0