如何生成用于绑定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 'System.Reflection.RuntimeModule'.
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)
答案 0 :(得分:0)
此行中发生了问题:
Context.Response.Write(serializer.Serialize(dt))
您正尝试将DataTable
实例直接序列化为JavaScriptSerializer
实例,该实例接受IEnumerable
或Dictionary(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字符串格式正确。