2017-08-30 123 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作爲類」

所有類都自動創建。我希望這個提示可以幫助你。