体式格局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//}; }
猎取的效果,申明,这类体式格局指定疏忽轮回援用,是在指定轮回级数后疏忽,返回的json数据中照样有部份轮回的数据
处理EF Json序列化轮回援用要领2,在指定的关联对象上,增加JsonIgnore 要领解释
[JsonIgnore]public virtual ICollection<score> scores { get; set; }
返回效果中,没有关联表数据
文章转载自:
以上就是ASP.NET MVC 碰到JSON轮回挪用的题目应当怎样处理?的细致内容,更多请关注ki4网别的相干文章!