2017-08-30 43 views
2

我想将一堆XML文件解析为单个JSON文件,该JSON文件已经在工作。Json在C中使用Json.net格式化#

最终的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" 
      }, 
... 

相反,我要实现以下结构:

{ 
"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" 
     } 
    ] 
] 
} 

但我不知道怎么做才能确定我的对象这样做,我现在的结构如下:

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; } 
} 

我应该怎么做?

回答

5

答案很简单:把你的对象变成列表:这将删除prop名称(和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; } 
} 

正如@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; } 
} 
+1

从列表继承的注意通常被认为是[坏习惯](https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt)。 –

+0

然后直接使用'公开列表<列表>项目';将是最好的解决方案。 –

1

复制那么你的JSON走在Visual Studio。
点击“编辑”>“选择性粘贴”>“粘贴JSON作为类”

所有类都自动创建。我希望这个提示可以帮助你。