我有这个JSON文本,我无法弄清楚如何解析“items”属性来填充项目列表
{
"response": {
"success": 1,
"current_time": 1445015502,
"items": {
"item1": {
"property1": 1,
"property2": "test",
"property3": 4.3
},
"item2": {
"property1": 5,
"property2": "test2",
"property3": 7.8
}
}
}
}
这些是我的课程:
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; }
}
另外,不,这不是错误。 JSON文本中没有[
和]
。
此外,JSON中的项目数量未定义。
答案 0 :(得分:3)
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;
}
答案 1 :(得分:0)
items
不是JSON中的数组,它是一个对象:
"items": {
"item1": {
"property1": 1,
"property2": "test",
"property3": 4.3
},
"item2": {
"property1": 5,
"property2": "test2",
"property3": 7.8
}
}
因此它不会反序列化为集合:
public List<Item> items { get; set; }
相反,为它创建一个类型:
public class Items
{
public Item item1 { get; set; }
public Item item2 { get; set; }
}
并在父对象中使用它:
public class Response
{
public int success { get; set; }
public string message { get; set; }
public int current_time { get; set; }
public Items items { get; set; }
}