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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With