Json循环引用问题
I am trying to do a simple JSON return but I am having issues I have the following below.
public JsonResult GetEventData()
{
var data = Event.Find(x => x.ID != 0);
return Json(data);
}
I get a HTTP 500 with the exception as shown in the title of this question. I also tried
var data = Event.All().ToList()
That gave the same problem.
Is this a bug or my implementation?
It seems that there are circular references in your object hierarchy which is not supported by the JSON serializer. Do you need all the columns? You could pick up only the properties you need in the view:
return Json(new
{
PropertyINeed1 = data.PropertyINeed1,
PropertyINeed2 = data.PropertyINeed2
});
This will make your JSON object lighter and easier to understand. If you have many properties, AutoMapper could be used to automatically map between DTO objects and View objects.
I had the same problem and solved by using Newtonsoft.Json;
var list = JsonConvert.SerializeObject(model,
Formatting.None,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return Content(list, "application/json");
This actually happens because the complex objects are what makes the resulting json object fails. And it fails because when the object is mapped it maps the children, which maps their parents, making a circular reference to occur. Json would take infinite time to serialize it, so it prevents the problem with the exception.
Entity Framework mapping also produces the same behavior, and the solution is to discard all unwanted properties.
Just expliciting the final answer, the whole code would be:
public JsonResult getJson()
{
DataContext db = new DataContext ();
return this.Json(
new {
Result = (from obj in db.Things select new {Id = obj.Id, Name = obj.Name})
}
, JsonRequestBehavior.AllowGet
);
}
It could also be the following in case you don't want the objects inside a Result
property:
public JsonResult getJson()
{
DataContext db = new DataContext ();
return this.Json(
(from obj in db.Things select new {Id = obj.Id, Name = obj.Name})
, JsonRequestBehavior.AllowGet
);
}
To sum things up, there are 3 solutions to this:
private DBEntities db = new DBEntities();//dbcontext
//Solution 1: turn off ProxyCreation for the DBContext and restore it in the end
public ActionResult Index()
{
bool proxyCreation = db.Configuration.ProxyCreationEnabled;
try
{
//set ProxyCreation to false
db.Configuration.ProxyCreationEnabled = false;
var data = db.Products.ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
finally
{
//restore ProxyCreation to its original state
db.Configuration.ProxyCreationEnabled = proxyCreation;
}
}
//Solution 2: Using JsonConvert by Setting ReferenceLoopHandling to ignore on the serializer settings.
//using using Newtonsoft.Json;
public ActionResult Index()
{
try
{
var data = db.Products.ToList();
JsonSerializerSettings jss = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
var result = JsonConvert.SerializeObject(data, Formatting.Indented, jss);
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
}
//Solution 3: return a new dynamic object which includes only the needed properties.
public ActionResult Index()
{
try
{
var data = db.Products.Select(p => new
{
Product_ID = p.Product_ID,
Product_Name = p.Product_Name,
Product_Price = p.Product_Price
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
}
ts because of the new DbContext T4 template that is used for generating the EntityFramework entities. In order to be able to perform the change tracking, this templates uses the Proxy pattern, by wrapping your nice POCOs with them. This then causes the issues when serializing with the JavaScriptSerializer.
So then the 2 solutions are:
- Either you just serialize and return the properties you need on the client
You may switch off the automatic generation of proxies by setting it on the context's configuration
context.Configuration.ProxyCreationEnabled = false;
Very well explained in the below article.
http://juristr.com/blog/2011/08/javascriptserializer-circular-reference/
Json循环引用问题的更多相关文章
- 【JSON 注解】JSON循环引用2----JSON注解@JsonIgnoreProperties+JAVA关键字transient+后台对象与JSON数据的格式互相转化
接着来说这个JSON循环引用的问题: 关于JSON格式的转化,其实关键就是这几个依赖: <!-- json --> <!-- 1号 --> <dependency> ...
- 【JSON 注解】JSON循环引用1-----Jackson常用注解介绍 eq:@JsonIgnore
循环引用:实体A与实体B有关系,A中有B作为字段,B中有A作为一个字段.查询A对象后,将A对象转化为JSON格式数据时,会因为序列化过程中导致A中有B字段,B字段中又有A,这样就引起了循环引用的问题! ...
- webapi修改tt模板给字段添加JsonIgnore特性解决转换json循环引用问题
0.问题描述 EF生成的model带有导航属性,则json序列化会报循环引用错误,尝试如下 protected void Application_Start() { GlobalConfigurati ...
- [MVC_Json序列化]MVC之Json序列化循环引用
在做MVC项目时,难免会遇到Json序列化循环引用的问题,大致错误如下 错误1:序列化类型为“...”的对象时检测到循环引用. 错误2:Self referencing loop detected f ...
- Json.net对于导航属性的处理(解决对象循环引用)
对于两张表A.B多对多的关系中,A的导航属性中有B,B的导航属性中有A,这样Json.net对A或者B对象序列化时会形成死循环 所以对于导航属性要加标签 首先在A.B实体类工程(Model)中引用Js ...
- Atitit.json xml 序列化循环引用解决方案json
Atitit.json xml 序列化循环引用解决方案json 1. 循环引用1 2. 序列化循环引用解决方法1 2.1. 自定义序列化器1 2.2. 排除策略1 2.3. 设置序列化层次,一般3级别 ...
- 解决MVC Json序列化的循环引用问题/EF Json序列化循引用问题---Newtonsoft.Json
1..Net开源Json序列化工具Newtonsoft.Json中提供了解决序列化的循环引用问题: 方式1:指定Json序列化配置为 ReferenceLoopHandling.Ignore 方式2: ...
- 解决.Net MVC EntityFramework Json 序列化循环引用问题.
以前都是到处看博客,今天小菜也做点贡献,希望能帮到大家. 废话不多说,直接进入正题. 用过.net MVC的同学应该都被json序列化报循环引用错误这个问题骚扰过.网上有一些解决办法,但是都治标不治本 ...
- 小解系列-自关联对象.Net MVC中 json序列化循环引用问题
自关联对象在实际开发中用的还是比较多,例如常见的树形菜单.本文是自己实际的一个小测试,可以解决循环引用对象的json序列化问题,文笔不好请多见谅,如有错误请指出,希望有更好的解决方案,一起进步. 构造 ...
随机推荐
- 理解JavaScript函数参数
前面的话 javascript函数的参数与大多数其他语言的函数的参数有所不同.函数不介意传递进来多少个参数,也不在乎传进来的参数是什么数据类型,甚至可以不传参数. arguments javascri ...
- Android Activity 及其子类
本文内容 ListActivity TabActivity LauncherActivity ExpandableListActivity PerferenceActivity 这些类都继承 Acti ...
- GOOD BLOG URL
1TEST http://www.cnblogs.com/Javame/p/3653509.html 综合 http://shiyanjun.cn/
- 从#!/bin/bash中想到的...
罪过罪过,开发了N年的SHELL,竟然第一次思考#!/bin/bash是啥意思?真是怀疑以前的的代码是咋开发出来的- 如果要解释#!/bin/bash是啥意思?为啥每个SHELL脚本第一行都写它哪?首 ...
- 前台登录和Token信息交互流程
原来总是对前台登录,怎么利用token有点迷惑,后面仔细的想了一遍,把自己简单的想法记录下来,留作记录,以便后续优化 各路大神有什么看法也可以说,能更完善整个流程. 不说了,暴力的上图: 该图是出自c ...
- 使用 loop device 制作安装镜像
看了下,手上的镜像中,文件系统才 100 多兆,但是整个镜像居然要 4G, 这意味着,我每次安装这个镜像到 SD 卡都要花很多没必要的时间. 所以,我提取了一些关键内容,然后,准备重新打包镜像. 1. ...
- android ndk native错误分析方法
使用ndk自带的工具进行分析, /mnt/d/Projects/linuxEnv/env/toolchains/aarch64-linux-android-4.9/bin/aarch64-linux- ...
- iOS变量定义在 .h 还是 .m 中
前言 曾经我定义变量一直都是定义在.h文件里.后来看别人的代码,发现非常多人都把一些变量定 义在.m文件里. 后来我自己试了一把,发现变量既能够定义在.h文件里也能够定义在.m文 件中,尽管这是个非常 ...
- 〖Linux〗Ubuntu13.10搭建文件共享Samba服务器
1. 安装 $ sudo apt-get install samba 2. 配置smb用户密码 # cat /etc/passwd | mksmbpasswd > /etc/samba/smbp ...
- 关于RSA加密算法的工具类
关于RSA加密算法的工具类 最近在捣鼓SSO(单点登录),就是一个在应用(系统)登录之后,当切换其他应用(系统)的时候,可以省去登录,提高用户的使用的便捷.(具体有时间在写) 期间涉及的安全问题,发送 ...