2

I have a list of two DataTables. I'm converting this list to a JSON array, but I need to add the table name for every DataTable in the JSON string.

How can I do that?

This is how I'm converting the list:

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

Desired JSON output:

{
    "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"
        }
    ]
}
2
  • can you post an example of the JSON you'd like to get? Commented Oct 24, 2013 at 7:13
  • @onof i updated my question kindly check Commented Oct 24, 2013 at 7:23

1 Answer 1

2

Try putting your tables into a DataSet instead of a list, then serialize the 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)

Output:

{
  "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"
    }
  ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.