Zacharias
Zacharias

Reputation: 13

Serialize nested JSON string using a datatable

I have this JSON string:

{
  "DataflowID": 1234,
  "Data": [    
    {
      "Key": "TIMESTAMP",
      "Value": "2019/11/11 07:00:00"
    },
    {
      "Key": "test1",
      "Value": "5.819720684"
    },
    {
      "Key": "test2",
      "Value": "12.47921946"
    }
  ]
}

And I am using the below code to get the data from the database and make the JSON string:

Imports Newtonsoft.Json

        Dim dataSet As DataSet = New DataSet("dataSet")
        dataSet.[Namespace] = "NetFrameWork"
        Dim jsonTable As DataTable = New DataTable()
        Dim keyColumn As DataColumn = New DataColumn("Key")
        Dim valueColumn As DataColumn = New DataColumn("Value")
        jsonTable.Columns.Add(keyColumn)
        jsonTable.Columns.Add(valueColumn)
        dataSet.Tables.Add(jsonTable)

        jsonTable.TableName = "Data"

        For m = 1 To g
            Dim dataRow2 As DataRow = jsonTable.NewRow
            dataRow2("Key") = "Timestamp"
            dataRow2("Value") = testTimestamp(m)
            jsonTable.Rows.Add(dataRow2)

            For k = 1 To tagsCounter
                Dim dataRow1 As DataRow = jsonTable.NewRow
                dataRow1("Key") = testName(k)
                dataRow1("Value") = testValue(m, k)
                jsonTable.Rows.Add(dataRow1)
            Next k
        Next m

But I cannot make the property dataFlowID .

Upvotes: 1

Views: 311

Answers (1)

theduck
theduck

Reputation: 2617

I would build a class to represent the JSON and fill it in. For example:

Public Class JsonHolder
    Public DataflowId As Integer
    Public Data As DataTable
End Class

It looks like you already have the Data part sorted, so you just need to put that into a new instance of this holder class along with the DataflowId:

Dim holder = New JsonHolder With {
    .DataflowId = 1234,
    .Data = jsonTable
}

Then use Newtonsoft to serialise to JSON:

Dim json = JsonConvert.SerializeObject(holder, Formatting.Indented)

Upvotes: 1

Related Questions