我有两个DataTable
的列表。我正在将此列表转换为JSON数组,但我需要在JSON字符串中为每个DataTable
添加表名。
我该怎么做?
这就是我转换列表的方式:
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 :(得分: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"
}
]
}