1..Net開源Json序列化工具Newtonsoft.Json中提供了解決序列化的循環引用問題:
方式1:指定Json序列化配置為 ReferenceLoopHandling.Ignore
#方式2:指定JsonIgnore忽略引用物件
##實例1,解決MVC的Json序列化參考方法:
step1:在專案上新增引用Newtonsoft.Json程式包,指令:Insert-Package Newtonsoft.Json
#step2:在專案中加入一個類,繼承JsonResult,程式碼如下:


#
/// <summary>/// 继承JsonResut,重写序列化方式/// </summary>public class JsonNetResult : JsonResult
{public JsonSerializerSettings Settings { get; private set; }public JsonNetResult()
{
Settings = new JsonSerializerSettings
{//这句是解决问题的关键,也就是json.net官方给出的解决配置选项.
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
}public override void ExecuteResult(ControllerContext context)
{if (context == null)throw new ArgumentNullException("context");if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))throw new InvalidOperationException("JSON GET is not allowed");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;if (this.Data == null)return;var scriptSerializer = JsonSerializer.Create(this.Settings);using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
response.Write(sw.ToString());
}
}
}
登入後複製

#step3:在專案中加入BaseController,重寫Json()方法,程式碼如下:


public class BaseController : Controller
{public StudentContext _Context = new StudentContext();/// <summary>/// 重写,Json方法,使之返回JsonNetResult类型/// </summary>protected override JsonResult Json(object data, string contentType,
Encoding contentEncoding, JsonRequestBehavior behavior)
{return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
}
登入後複製
step4.往平常一樣使用就可以了


#
//获取列表public JsonResult GetList()
{
List<student> list = _Context.students.Where(q => q.sno == "103").ToList();//方法1return Json(list);//方法2//return new JsonNetResult() {// Data=list//};
}</student>
登入後複製

所取得的結果,說明,這種方式指定忽略循環引用,是在指定循環級數後忽略,返回的json資料中還是有部分循環的資料

解決EF Json序列化循環參考方法2,在指定的關聯物件上,新增JsonIgnore 方法註解
#
[JsonIgnore]public virtual ICollection<score> scores { get; set; }</score>
登入後複製
#########傳回結果中,沒有關聯表資料###########################文章轉載自:# ########
以上是ASP.NET MVC 遇到JSON循環呼叫的問題該怎麼解決?的詳細內容。更多資訊請關注PHP中文網其他相關文章!