vb.net datatable Serialize to json

后端 未结 2 649
死守一世寂寞
死守一世寂寞 2021-01-05 02:22

I have this kind of table:

\"\"

I need to get this JSON (of course order could be any, structure/tree

2条回答
  •  渐次进展
    2021-01-05 03:11

    Here is my solution:

    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
    
        Try
            Dim result() As DataRow = dt.Select("Parent_ = 'main'")
            Dim i As Integer
            For i = 0 To result.GetUpperBound(0)
                row = New Dictionary(Of String, Object)()
                If UCase(result(i)(2)) <> "HAS CHILD" Then
                    row.Add(result(i)(0), result(i)(2))
                Else
                    row.Add(result(i)(0), add_(dt, result(i)(0)))
                End If
                packet.Add(row)
            Next i
    
            Return serializer.Serialize(packet)
        Catch ex As Exception
            MsgBox(ex.ToString)
            Me.Close()
        End Try
    
    End Function
    
    Public Function add_(ByVal dt As System.Data.DataTable, ByVal parent_ As String) As Dictionary(Of String, Object)
        Dim row As Dictionary(Of String, Object) = Nothing
        Try
            Dim result() As DataRow = dt.Select("Parent_ = '" & parent_ & "'")
            Dim i As Integer
            row = New Dictionary(Of String, Object)()
            For i = 0 To result.GetUpperBound(0)
    
                If UCase(result(i)(2)) <> "HAS CHILD" Then
                    row.Add(result(i)(0), result(i)(2))
                Else
                    row.Add(result(i)(0), add_(dt, result(i)(0)))
                End If
            Next i
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        Return row
    End Function
    

提交回复
热议问题