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:

  1. Either you just serialize and return the properties you need on the client
  2. 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循环引用问题的更多相关文章

  1. 【JSON 注解】JSON循环引用2----JSON注解@JsonIgnoreProperties+JAVA关键字transient+后台对象与JSON数据的格式互相转化

    接着来说这个JSON循环引用的问题: 关于JSON格式的转化,其实关键就是这几个依赖: <!-- json --> <!-- 1号 --> <dependency> ...

  2. 【JSON 注解】JSON循环引用1-----Jackson常用注解介绍 eq:@JsonIgnore

    循环引用:实体A与实体B有关系,A中有B作为字段,B中有A作为一个字段.查询A对象后,将A对象转化为JSON格式数据时,会因为序列化过程中导致A中有B字段,B字段中又有A,这样就引起了循环引用的问题! ...

  3. webapi修改tt模板给字段添加JsonIgnore特性解决转换json循环引用问题

    0.问题描述 EF生成的model带有导航属性,则json序列化会报循环引用错误,尝试如下 protected void Application_Start() { GlobalConfigurati ...

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

    在做MVC项目时,难免会遇到Json序列化循环引用的问题,大致错误如下 错误1:序列化类型为“...”的对象时检测到循环引用. 错误2:Self referencing loop detected f ...

  5. Json.net对于导航属性的处理(解决对象循环引用)

    对于两张表A.B多对多的关系中,A的导航属性中有B,B的导航属性中有A,这样Json.net对A或者B对象序列化时会形成死循环 所以对于导航属性要加标签 首先在A.B实体类工程(Model)中引用Js ...

  6. Atitit.json xml 序列化循环引用解决方案json

    Atitit.json xml 序列化循环引用解决方案json 1. 循环引用1 2. 序列化循环引用解决方法1 2.1. 自定义序列化器1 2.2. 排除策略1 2.3. 设置序列化层次,一般3级别 ...

  7. 解决MVC Json序列化的循环引用问题/EF Json序列化循引用问题---Newtonsoft.Json

    1..Net开源Json序列化工具Newtonsoft.Json中提供了解决序列化的循环引用问题: 方式1:指定Json序列化配置为 ReferenceLoopHandling.Ignore 方式2: ...

  8. 解决.Net MVC EntityFramework Json 序列化循环引用问题.

    以前都是到处看博客,今天小菜也做点贡献,希望能帮到大家. 废话不多说,直接进入正题. 用过.net MVC的同学应该都被json序列化报循环引用错误这个问题骚扰过.网上有一些解决办法,但是都治标不治本 ...

  9. 小解系列-自关联对象.Net MVC中 json序列化循环引用问题

    自关联对象在实际开发中用的还是比较多,例如常见的树形菜单.本文是自己实际的一个小测试,可以解决循环引用对象的json序列化问题,文笔不好请多见谅,如有错误请指出,希望有更好的解决方案,一起进步. 构造 ...

随机推荐

  1. (转)Unity3D 游戏贴图(法线贴图,漫反射贴图,高光贴图)

    原帖网址http://www.u3dpro.com/read.php?tid=207  感谢jdk900网友的辛苦编写 我们都知道,一个三维场景的画面的好坏,百分之四十取决于模型,百分之六十取决于贴图 ...

  2. 数据科学家Docker历险记(1):windows下环境搭建

    原文:http://www.xueqing.tv/cms/article/247 Docker是最近炒得很火热的一门技术,在网上可以找到关于它的介绍文章,比如<Docker到底是什么?为什么它这 ...

  3. 可以在任何时候attach一个shader到program对象

      可以在任何时候attach一个shader到program对象,不一定非要在指定source和编译以后,具体的描述如下: Once you have a program object create ...

  4. [Docker] Building a Node.js Image

    Create a Dockerfile: FROM node:latest MAINTAINER Zhentian Wan ENV NODE_ENV=production ENV PORT= COPY ...

  5. GPUImage API文档之GPUImageFramebufferCache类

    GPUImageFramebufferCache类负责管理GPUImageFramebuffer对象,是一个GPUImageFramebuffer对象的缓存. 方法 - (GPUImageFrameb ...

  6. WIN7系统开题提示loli.vbs 操作超时怎么办

    这个是魔兽争霸的一个病毒,但是该病毒没有任何危害性,只是作为检测进入房间的地图是否含有作弊脚本,主动提供了清除工具   搜索loli,删除所有bat和exe,vbs文件   如果魔兽争霸3安装目录存在 ...

  7. 【POJ 3071】 Football(DP)

    [POJ 3071] Football(DP) Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 4350   Accepted ...

  8. 使用windbg抓取崩溃文件和分析的过程

    在软件编程中,崩溃的场景比较常见的.且说微软技术再牛X,也是会出现崩溃的场景.网上有一段Win98当着比尔盖茨蓝屏的视频非常有意思. (转载请指明出于breaksoftware的csdn博客)     ...

  9. TP - 001

  10. 前端安全系列(一):如何防止XSS攻击?

    原文:https://my.oschina.net/meituantech/blog/2218539 前端安全 随着互联网的高速发展,信息安全问题已经成为企业最为关注的焦点之一,而前端又是引发企业安全 ...