Reading JSON when an array is presented as objects with the properties "item # XXX"

I have this JSON text and I can’t figure out how to parse the β€œitems” property to populate a list of items

{ "response": { "success": 1, "current_time": 1445015502, "items": { "item1": { "property1": 1, "property2": "test", "property3": 4.3 }, "item2": { "property1": 5, "property2": "test2", "property3": 7.8 } } } } 

These are also my classes:

 public class Item { public int property1 { get; set; } public string property2 { get; set; } public double property3 { get; set; } } public class Response { public int success { get; set; } public string message { get; set; } public int current_time { get; set; } public List<Item> items { get; set; } } public class RootObject { public Response response { get; set; } } 

Also, no, this is not a mistake. There is no [ and ] JSON text. In addition, the number of elements in JSON is undefined.

+5
source share
2 answers

This is easy to do thanks to Json.NET and dynamic :

 private RootObject Parse(string jsonString) { dynamic jsonObject = JsonConvert.DeserializeObject(jsonString); RootObject parsed = new RootObject() { response = new Response() { success = jsonObject.response.success, current_time = jsonObject.response.current_time, message = jsonObject.response.message, items = ParseItems(jsonObject.response.items) } }; return parsed; } private List<Item> ParseItems(dynamic items) { List<Item> itemList = new List<Item>(); foreach (var item in items) { itemList.Add(new Item() { property1 = item.Value.property1, property2 = item.Value.property2, property3 = item.Value.property3 }); } return itemList; } 
+4
source

items not an int he JSON array, this is an object:

 "items": { "item1": { "property1": 1, "property2": "test", "property3": 4.3 }, "item2": { "property1": 5, "property2": "test2", "property3": 7.8 } } 

Therefore, it will not be deserialized into the collection:

 public List<Item> items { get; set; } 

Instead, create a type for it:

 public class Items { public Item item1 { get; set; } public Item item2 { get; set; } } 

And use this in the parent object:

 public class Response { public int success { get; set; } public string message { get; set; } public int current_time { get; set; } public Items items { get; set; } } 
0
source

Source: https://habr.com/ru/post/1233884/


All Articles