The 1..Net Open source JSON serialization tool Newtonsoft.json provides a circular reference problem to solve serialization:
Method 1: Specify the JSON serialization configuration as Referenceloophandling.ignore
Method 2: Specify Jsonignore to ignore reference objects
Example 1, solving the MVC JSON serialization reference method:
Step1: Add Reference Newtonsoft.json package on Project, command: Insert-package Newtonsoft.json
Step2: Add a class to the project, inherit Jsonresult, and the code is as follows:
<summary>///inherits Jsonresut, rewrites the serialization method///</summary>public class Jsonnetresult:jsonresult{public Jsonserializersettings Settings {get; private set;} Public Jsonnetresult () {Settings = new Jsonserializersettings {///This is the key to solving the problem, which is the solution configuration option given by the Json.NET authorities. referenceloophandling = Referenceloophandling.ignore}; }public override void Executeresult (ControllerContext context) {if (context = = null) throw new ArgumentNullException ("Co ntext "); 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, rewrite the JSON () method, and the code is as follows:
public class Basecontroller:controller{public Studentcontext _context = new Studentcontext ();///<summary>///rewrite, Json method to return the Jsonnetresult type//</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. Use it as you normally would.
Gets the list public Jsonresult GetList () { list<student> list = _context.students.where (q = = Q.sno = "103"). ToList ();//Method 1return Json (list);//Method 2//return new Jsonnetresult () {// data=list//};}
Gets the result, which specifies that the ignore circular reference is ignored after the specified loop series, and that the returned JSON data is partially looped in data
Resolve EF JSON Serialization Circular reference Method 2, add Jsonignore method comment on the specified associated object
[Jsonignore]public virtual icollection<score> scores {get; set;}
Returned results, no associated table data
Articles reproduced from: