[英]Convert a .Net object to JSON
從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。 代碼如下。 但是,即使返回的JSON中存在d.TotalCount和d.Data,瀏覽器也無法理解。
[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充滿了反斜杠,瀏覽器無法解釋這些反斜杠。 不會從JSON字符串中解析d.Data和d.TotalCount。 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 ,許多人會說它是可用的最佳Json序列化程序之一,我在所有項目中都使用它。
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"
// }
// }
// ]
// }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.