2017-08-09 112 views
1

我從服務器返回這JSON,jQuery的數據表,但它會返回錯誤:序列化類型錯誤的對象時檢測到循環引用?

System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'. 
    at WebServices.himher.getUsers1(Int32 iDisplayLength, Int32 iDisplayStart, Int32 iSortCol_0, String sSortDir_0, String sSearch) 

的.cs代碼:

public void getUsers1(int iDisplayLength, int iDisplayStart, int iSortCol_0, string sSortDir_0, string sSearch) 
{ 
    try 
    { 
     basicoperation bop = new basicoperation(); 
     DataTable dt; 

     dt = bop.getUsers(iDisplayLength, iDisplayStart, iSortCol_0, sSortDir_0, sSearch); // fetching users 

     dt.TableName = "usersDT1"; 

     //int iTotalRecords=0; 
     //int iTotalDisplayRecords= 0; 

     var retObj = new 
     { 
      iTotalRecords= 20, 
      iTotalDisplayRecords= 10, 
      aaData= dt 
     }; 

     //string json = JsonConvert.SerializeObject(dt); 

     JavaScriptSerializer js = new JavaScriptSerializer(); 

     Context.Response.Write(js.Serialize(retObj)); 
    } 
    catch (Exception ex) 
    { 

     throw ex; 
    } 
} 
+0

異常消息非常清晰。您的數據模型中有一個無法序列化的循環引用。使DTO成爲僅應該到達視圖的僅選擇數據,而不是整個數據表 – Alex

回答

4

的問題是,你retObj包含DataTable,這不可能按原樣序列化爲JSON,因爲它內部有循環引用。

本文展示不同的方式來串行化數據表;

http://www.c-sharpcorner.com/UploadFile/9bff34/3-ways-to-convert-datatable-to-json-string-in-Asp-Net-C-Sharp/

我首選的可能是最後的辦法

using Newtonsoft.JSON; 

public string DataTableToJSONWithJSONNet(DataTable table) { 
    string JSONString=string.Empty; 
    JSONString = JSONConvert.SerializeObject(table); 
    return JSONString; 
} 
0

這是很清楚的,你在你的代碼aaData= dt在這裏有一個循環引用。
您可以使用下面的代碼來解決這個問題,

JsonConvert.SerializeObject(retObj, Formatting.None, 
        new JsonSerializerSettings {ReferenceLoopHandling = 
              ReferenceLoopHandling.Ignore}); 
-1

一種更簡便的方法來解決這個問題是返回一個字符串,格式化字符串JavaScriptSerializer到JSON。

public string GetEntityInJson() 
{ 
    JavaScriptSerializer j = new JavaScriptSerializer(); 
    var entityList = dataContext.Entitites.Select(x => new { ID = x.ID, AnotherAttribute = x.AnotherAttribute }); 
    return j.Serialize(entityList); 
} 

重要的是「選擇」部分,它選擇你想要在你的視圖中的屬性。某些對象有父母的參考。如果您不選擇屬性,則可能會出現循環引用,如果您只是整個表格。

不要這樣做:

public string GetEntityInJson() 
{ 
    JavaScriptSerializer j = new JavaScriptSerializer(); 
    var entityList = dataContext.Entitites.toList(); 
    return j.Serialize(entityList); 
} 

而是執行此操作,如果你不希望整個表:

public string GetEntityInJson() 
{ 
    JavaScriptSerializer j = new JavaScriptSerializer(); 
    var entityList = dataContext.Entitites.Select(x => new { ID = x.ID, AnotherAttribute = x.AnotherAttribute }); 
    return j.Serialize(entityList); 
} 

這有助於使較少的數據來看,正好與你的屬性需要,並使您的網絡運行更快。

相關問題