JSON数组字符串中的表名

时间:2013-10-24 07:11:00

标签: json vb.net datatable json.net

我有两个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"
        }
    ]
}

1 个答案:

答案 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"
    }
  ]
}