webapi修改tt模板给字段添加JsonIgnore特性解决转换json循环引用问题
0.问题描述
EF生成的model带有导航属性,则json序列化会报循环引用错误,尝试如下
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
////config.Formatters.JsonFormatter.MediaTypeMappings.Add(new System.Net.Http.Formatting.QueryStringMapping("datatype", "json", "application/json"));/*http://www.cnblogs.com/mirrortom/p/5931573.html*/
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();//清除xml序列化
//HttpConfiguration config = GlobalConfiguration.Configuration;
////config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
//config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
}
均无法解决.经搜索发现可以修改tt模板,给字段添加JsonIgnore特性
1.观察edmx生成的model字段
发现导航属性都是virtual,并且标记有特性[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
2.修改tt模板,添加JsonIgnore特性
找到edmx文件下的.tt文件
搜索[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
并在此行之上添加一行
[Newtonsoft.Json.JsonIgnore]
添加后
3.项目添加NewtonSoftJson.dll的引用并编译
此时controller里直接返回db.Table1.ToList();不会发生循环引用
From:http://www.cnblogs.com/xuejianxiyang/p/6204111.html
- 在springmvc中解决FastJson循环引用的问题
- 用JAXB转换XML和Java对象时的循环引用问题的解决方法
- 在springmvc中解决FastJson循环引用的问题
- 【FastJSON】解决FastJson中“$ref 循环引用”的问题
- 解决.Net MVC EntityFramework Json 序列化循环引用问题.
- 解决FastJson的$ref循环引用检测的问题
- springmvc中解决FastJson循环引用的问题
- [C#] .NET Core项目修改project.json来引用其他目录下的源码等文件的办法 & 解决多框架时 project.json 与 app.config冲突的问题
- 解决MVC Json序列化的循环引用问题/EF Json序列化循引用问题(Newtonsoft.Json)
- 解决MVC Json序列化的循环引用问题/EF Json序列化循引用问题---Newtonsoft.Json
- 在springmvc中解决FastJson循环引用的问题
- extjs解决bean转换为json对象的死循环的问题
- EntityFramework中Json序列化的循环引用问题解决--Newtonsoft.Json
- 【FastJSON】解决FastJson中“$ref 循环引用”的问题
- 【FastJSON】解决FastJson中“$ref 循环引用”的问题
- 解决.Net MVC EntityFramework Json 序列化循环引用问题.
- 解决fastjson循环引用问题(死循环)
- discuz x2 个人资料项排序问题解决方法、添加自定义字段、修改栏目名称和介绍
- springmvc中解决FastJson循环引用的问题
- 详解在springmvc中解决FastJson循环引用的问题