如何为JQUERY数据表返回JSON数据?

时间:2018-11-29 07:11:29

标签: jquery asp.net json vb.net datatable

如何生成用于绑定JQUERY数据表的JSON数据?

我在ASP.net Web服务(.asmx)中使用以下代码

<WebMethod()> _
Public Function Getcdata() As String
    Dim dt As New DataTable()
    Using con As New SqlConnection(IDvar.Constr)
        Using cmd As New SqlCommand("Select * from COMPLAINTTYPE", con)

            con.Open()
            Dim da As New SqlDataAdapter(cmd)
            da.Fill(dt)
            Dim serializer As 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)()
                rows.Add(row)
            Next
            Context.Response.Write(serializer.Serialize(dt))

            con.Close()
            cmd.Dispose()
            dt.Clear()
        End Using
    End Using
End Function

但是这将返回错误。请检查我错了

调用网络方法时遇到的错误如下:

System.InvalidOperationException: A circular reference was detected while serializing an object of type &#39;System.Reflection.RuntimeModule&#39;.
   at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)
   at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)
   at System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)

1 个答案:

答案 0 :(得分:0)

此行中发生了问题:

Context.Response.Write(serializer.Serialize(dt))

您正尝试将DataTable实例直接序列化为JavaScriptSerializer实例,该实例接受IEnumerableDictionary(Of TKey, TValue)之类的集合对象。通常,您需要使用AsEnumerable()[Select]() LINQ方法转换为IEnumerable

Dim list = dt.AsEnumerable().[Select](Function(row) New With { Key
    .id = row("COMPLAINTID"), Key
    .name = row("COMPLAINTNAME"), 

    ' other DataTable columns here
}).ToList()

Context.Response.Write(serializer.Serialize(list))

但是由于您有Dictionary(Of String, Object)包含要进行序列化的对象的列表,因此只需将字典传递给序列化器即可,而不要传递DataTable

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)()
    rows.Add(row)
Next

' pass the list of dictionary here
Context.Response.Write(serializer.Serialize(rows))

旁注:

您可以尝试使用JSON.NET中的JsonConvert.SerializeObject()方法来序列化包含Dictionary(Of TKey, TValue)对象的列表,与JavaScriptSerializer.Serialize()方法相比,该对象具有更好的字典处理能力。请注意,您应该检查输出以确保JSON字符串格式正确。