2

我有两个DataTables 的列表。我正在将此列表转换为 JSON 数组,但我需要为DataTableJSON 字符串中的每个添加表名。

我怎样才能做到这一点?

这就是我转换列表的方式:

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

1 回答 1

2

尝试将表放入 aDataSet而不是列表,然后序列化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"
    }
  ]
}
于 2013-10-24T08:13:20.800 回答