【发布时间】:2014-03-07 01:54:55
【问题描述】:
从 Web 服务方法中,我返回一个“GridBindingDataSet”类型的对象。但它不会自动序列化为 JSON。
有什么方法可以确保对象被序列化为 JSON? 我正在使用支持 AJAX 的 Web 服务,该服务可以使用 jQuery 从客户端调用。
public class GridBindingDataSet
{
public int TotalCount { get; set; }
public DataTable Data { get; set; }
}
编辑 1: 从 jQuery 调用 Web 服务方法时出现以下错误:
在序列化“System.Reflection.RuntimeModule”类型的对象时检测到循环引用
编辑 2: 我使用 JSON.net 来序列化 GridBindingDataSet 的上述对象。 Web 服务现在返回一个字符串而不是一个 GridBindingObject。代码如下。但是浏览器无法理解 d.TotalCount 和 d.Data ,即使它们在返回的 JSON 中也存在。
[WebMethod]
public string GetJSONDataSetForGrid()
{
...
...
DataTable dt = GetDataForPage0();
int total = GetTotalCount();
GridBindingDataSet gridBindingData = new GridBindingDataSet ( total, dt);
//return a JSON serialized string
return JsonConvert.SerializeObject(gridBindingData,
Formatting.None, new JsonSerializerSettings
{
PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None
});
}
但是返回的 JSON 充满了浏览器没有解释的反斜杠,因为使用 JSON 字符串的网格显示为空。 d.Data 和 d.TotalCount 没有从 JSON 字符串中解析。 返回的 JSON 如下:
{"d":"{\"TotalCount\":81,\"Data\":[{\"ProductName\":\"Alice Mutton\",\"UnitPrice\":39.00,
\"UnitsInStock\":0,\"Discontinued\":true},{\"ProductName\":\"Aniseed Syrup\",\"UnitPrice\":10.00,
\"UnitsInStock\":13,\"Discontinued\":false}]}"}
【问题讨论】:
-
JSON.net 似乎没问题stackoverflow.com/questions/2979922/… .. 不知道在“网络服务方法”案例中如何连接它。
-
But its not getting serialized as JSON automatically没有太多描述性。你有错误吗?你没想到会发生什么? -
@L.B - 我在帖子的 EDIT 1 下添加了我看到的错误。
-
@Maxwell Troy - 感谢您的评论。这很有帮助,但现在我需要找到如何在序列化 GridBindingDataSet 对象时使用数据表序列化。
-
如果你对双重序列化没问题,你可以使用 Json.Net 并从你的方法中返回一个
string。在 jQuery 中,您可以使用JSON.parse将字符串转换为真实对象。