首页 > Web开发 > 详细

[MVC_Json序列化]MVC之Json序列化循环引用

时间:2015-05-13 16:33:13      阅读:612      评论:0      收藏:0      [点我收藏+]

在做MVC项目时,难免会遇到Json序列化循环引用的问题,大致错误如下

错误1:序列化类型为“。。。”的对象时检测到循环引用。

错误2:Self referencing loop detected for property ‘。。。‘ with type ‘。。。‘. Path ‘[0].x[0]‘.

以上错误是因为数据库表关系引起的,比如一对一或多对多,如图:

技术分享

EF里面是这样的,如图:

技术分享

 

解决方法:

步骤1:

-引用JSON.NET

技术分享

 

步骤2:

-引用Newtonsoft.Json

技术分享

 

步骤3:

-Json序列化

public JsonResult Contact()
{
            
      var result = from score in context.Prarent
                     select score;
      string json = JsonConvert.SerializeObject(result, new JsonSerializerSettings
      {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
      });
      return Json(new { data = json }, JsonRequestBehavior.AllowGet);
}

返回的Json结果为:

技术分享

[MVC_Json序列化]MVC之Json序列化循环引用

原文:http://www.cnblogs.com/zhenhong/p/4500515.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!