2013-10-24 82 views
1

我有兩個DataTable s的列表。我將這個列表轉換爲JSON數組,但是我需要爲JSON字符串中的每個DataTable添加表名。JSON數組字符串中的表名

我該怎麼做?

這是我如何轉換列表:

Dim json As String = JsonConvert.SerializeObject(list, New DataTableConverter()) 

期望中的JSON輸出:

{ 
    "category": [ 
     { 
      "id": "1", 
      "desc": "default", 
     }, 
     { 
      "id": "2", 
      "desc": "fun", 
     } 
    ], 
    "images": [ 
     { 
      "image ID": "1", 
      "link": "images/logo.jpg" 
      "category": "1" 
     }, 
     { 
      "image ID": "2", 
      "link": "images/logo2.jpg" 
      "category": "2" 
     } 
    ] 
} 
+0

你可以發佈你想獲得JSON的例子嗎? – onof

+0

@onof我更新了我的問題,請檢查 – User7291

回答

1

嘗試把你的表成DataSet,而不是一個列表,然後序列化DataSet

Dim table1 As New DataTable("category") 
table1.Columns.Add("id", GetType(String)) 
table1.Columns.Add("desc", GetType(String)) 
table1.Rows.Add("1", "default") 
table1.Rows.Add("2", "fun") 

Dim table2 As New DataTable("images") 
table2.Columns.Add("image ID", GetType(String)) 
table2.Columns.Add("link", GetType(String)) 
table2.Columns.Add("category", GetType(String)) 
table2.Rows.Add("1", "images/logo.jpg", "1") 
table2.Rows.Add("2", "images/logo2.jpg", "2") 

Dim dataSet As New DataSet() 
dataSet.Tables.Add(table1) 
dataSet.Tables.Add(table2) 

Dim json As String = JsonConvert.SerializeObject(dataSet, Formatting.Indented) 

Console.WriteLine(json) 

輸出:

{ 
    "category": [ 
    { 
     "id": "1", 
     "desc": "default" 
    }, 
    { 
     "id": "2", 
     "desc": "fun" 
    } 
    ], 
    "images": [ 
    { 
     "image ID": "1", 
     "link": "images/logo.jpg", 
     "category": "1" 
    }, 
    { 
     "image ID": "2", 
     "link": "images/logo2.jpg", 
     "category": "2" 
    } 
    ] 
}