Lun*_*Dev 2 c# json jsonserializer json.net json-serialization
我试图将一堆XML文件解析为一个已经正常工作的JSON文件.
最终的JSON文件如下所示:
{
"items": [
{
"subItems": [
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
]
},
{
"subItems": [
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
...
Run Code Online (Sandbox Code Playgroud)
相反,我想实现以下结构:
{
"items": [
[
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
],
[
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
]
]
}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何定义我的对象才能这样做,我目前的结构如下:
public class Items
{
public List<Item> items;
}
public class Item
{
public List<SubItem> subItems;
}
public class SubItem
{
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
答案很简单:将对象转换为列表:这将删除道具名称(以及json中的对象表示法).
public class Items
{
public List<Item> items; //list with prop name 'items'
}
public class Item : List<SubItem> // list in list like json notation
{
}
public class SubItem // Object in the list in list
{
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
正如@FlilipCordas所说,从列表继承是不好的做法(有充分理由)你这样做更好:
public class Items
{
public List<List<SubItem>> items; //list with list with prop name 'items'
}
public class SubItem // Object in the list in list
{
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)