DataTable to Json using jquery

前端 未结 9 1208
抹茶落季
抹茶落季 2020-12-16 05:48

I\'m trying to execute a web service which returns a DataTable with the following piece of code:

$.ajax({  
    type: \"POST\",  
    url: url,  
    data: d         


        
9条回答
  •  独厮守ぢ
    2020-12-16 06:16

    In the end, I've decided to use the JavaScriptSerializer class to convert the DataTable into a JSON string. Unfortunately, this class doesn't work with a DataTable so I converted the DataTable into a list of dictionnaries and pass that list to the JavaScriptSerializer class. It takes only a few lines of code and it works fine.
    Example in VB.net:

        Public Function GetJson(ByVal dt As DataTable) As String
    
            Dim serializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
            Dim rows As New List(Of Dictionary(Of String, Object))
            Dim row As Dictionary(Of String, Object)
    
            For Each dr As DataRow In dt.Rows
                row = New Dictionary(Of String, Object)
                For Each col As DataColumn In dt.Columns
                    row.Add(col.ColumnName, dr(col))
                Next
                rows.Add(row)
            Next
            Return serializer.Serialize(rows)
        End Function
    

提交回复
热议问题