当数组表示为带有"item#XXX"的对象时,读取JSON.特性 [英] Read JSON when array represented as objects with "item#XXX" properties
本文介绍了当数组表示为带有"item#XXX"的对象时,读取JSON.特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个JSON文本,我不知道如何解析"items"属性来填充项目列表
I have this JSON text and I can't figure out how to parse the "items" property to fill up 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
}
}
}
}
那是我的课程吗:
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中的项目数是不确定的.
Also, no, it's not a error. There is no [
nor ]
in the JSON text.
Also, the number of items in the JSON is undefined.
推荐答案
由于 Json.NET,这很容易实现和动态:
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;
}
这篇关于当数组表示为带有"item#XXX"的对象时,读取JSON.特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文