Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vb.net datatable Serialize to json

I have this kind of table:

I need to get this JSON (of course order could be any, structure/tree is most important):

Data table can change, so serialization should be dynamic. I am working with vb.net and used this code:

 Public Function GetJson() As String
        Dim dt As New System.Data.DataTable
        dt = CreateDataTable() 'here I retrive data from oracle DB
        Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
        Dim packet As New List(Of Dictionary(Of String, Object))()
        Dim row As Dictionary(Of String, Object) = Nothing
        For Each dr As DataRow In dt.Rows
            row = New Dictionary(Of String, Object)()
            For Each dc As DataColumn In dt.Columns
                row.Add(dc.ColumnName.Trim(), dr(dc))
            Next
            packet.Add(row)
        Next
        Return serializer.Serialize(packet)
    End Function

But this code returns me bad json: [{"NAME":"city","PARENT":"address","VALUE":"has child"},{"NAME":"coordinates","PARENT":"address","VALUE":"has child"},{"NAME":"street","PARENT":"address","VALUE":"has child"}.......

Can someone help me out in here?

like image 208
innspiron Avatar asked Feb 08 '14 15:02

innspiron


1 Answers

The 'Oh-no you didn't' version:

Public Function GetJson(ByVal dt As DataTable) As String
    Return New JavaScriptSerializer().Serialize(From dr As DataRow In dt.Rows Select dt.Columns.Cast(Of DataColumn)().ToDictionary(Function(col) col.ColumnName, Function(col) dr(col)))
End Function
like image 104
Matthew Hudson Avatar answered Sep 21 '22 20:09

Matthew Hudson