1. The Net open source Json serialization tool Newtonsoft.Json provides a solution to the circular reference problem of serialization:
Method 1: Specify the Json serialization configuration as ReferenceLoopHandling.Ignore
Method 2: Specify JsonIgnore to ignore the reference object
Instance 1, solve the Json serialization reference method of MVC:
step1: Add a reference to the Newtonsoft.Json package on the project , Command: Insert-Package Newtonsoft.Json
step2: Add a class to the project, inheriting JsonResult, the code is as follows:
/// <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: Add BaseController to the project and rewrite the Json() method, the code is as follows:
To solve the EF Json serialization circular reference method 2, add the JsonIgnore method annotation on the specified associated object
[JsonIgnore]public virtual ICollection<score> scores { get; set; }</score>
The article is reproduced from:
The above is the detailed content of How to solve the problem of JSON loop call in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!