【问题标题】:Convert a .Net object to JSON将 .Net 对象转换为 JSON
【发布时间】: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 将字符串转换为真实对象。

标签: c# json


【解决方案1】:

同样值得一看 Json.Net,很多人会说这是可用的最好的 Json 序列化程序之一,我将它用于我的所有项目。

作为对循环引用的回应,请查看文档中的preserving references,来自他们的示例:

Directory root = new Directory { Name = "Root" };
Directory documents = new Directory { Name = "My Documents", Parent = root };

File file = new File { Name = "ImportantLegalDocument.docx", Parent = documents };

documents.Files = new List<File> { file };

string preserveReferenacesObjects = JsonConvert.SerializeObject(documents, Formatting.Indented, new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
});

// {
//   "$id": "1",
//   "Name": "My Documents",
//   "Parent": {
//     "$id": "2",
//     "Name": "Root",
//     "Parent": null,
//     "Files": null
//   },
//   "Files": [
//     {
//       "$id": "3",
//       "Name": "ImportantLegalDocument.docx",
//       "Parent": {
//         "$ref": "1"
//       }
//     }
//   ]
// }

【讨论】:

  • 循环引用呢?虽然 Json.Net 可以很好地处理它,但不是你发布的那样。
  • 根据您的评论更新了我的示例,感谢您的反馈。
  • 现在缺少的部分是:OP 将如何在他/她的代码中使用它? (在 aspx 和 jQuery 中)
猜你喜欢
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 2022-01-25
  • 2017-06-16
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多