EF 序列化实体为Json时的循环引用问题(不用自己写实体,不用匿名类型,不用EF的上下文属性)
自己写实体可以完美解决这个问题。(支持时间格式自定义)
用匿名类型也可以。
设置上下文方法如下:
(jz为数据库上下文对象)
jz.Configuration.ProxyCreationEnabled = false;
jz.Configuration.LazyLoadingEnabled = false;
不用这个的原因是Virtual属性也会生成。(只是占个位,[]里面没内容,但看着不爽)
我采用的方法是过滤掉Virtual属性的方法:
一个基于Json.net的类
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web; namespace AceepSystem.Models.Help
{
public class JsonForEF : DefaultContractResolver
{
string[] props = null; bool retain; /// <summary>
/// 构造函数
/// </summary>
/// <param name="props">传入的属性数组</param>
/// <param name="retain">true:表示props是需要保留的字段 false:表示props是要排除的字段</param>
public JsonForEF(string[] props, bool retain = true)
{
//指定要序列化属性的清单
this.props = props; this.retain = retain;
} protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> list =
base.CreateProperties(type, memberSerialization);
//只保留清单有列出的属性
return list.Where(p =>
{
if (retain)
{
return props.Contains(p.PropertyName);
}
else
{
return !props.Contains(p.PropertyName);
}
}).ToList();
}
public static string[] GetVirtualList<T>()
{
var stringType = typeof(T);
var props = stringType.GetProperties();
List<string> test = new List<string>();
foreach (var prop in props)
{
if (prop.GetAccessors()[0].IsVirtual)
{
test.Add(prop.Name);
}
}
return test.ToArray();
}
public static JsonSerializerSettings GetJsonConfig<T>()
{ JsonSerializerSettings jsetting = new JsonSerializerSettings();//过滤掉ef中的导航属性,无残留...
jsetting.ContractResolver = new JsonForEF(
JsonForEF.GetVirtualList<T>()//泛型方法传入当前要序列化的类型
, false);//false为要排除的属性,true为要保留的属性(第一个参数为string[])
jsetting.Converters.Add(new MyDateTimeConvertor());
return jsetting;
}
public class MyDateTimeConvertor : DateTimeConverterBase
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return DateTime.Parse(reader.Value.ToString());
} public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((DateTime)value).ToString("yyyy/MM/dd HH:mm"));
}
}
}
}
和一个对PropertyInfo的扩展方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web; namespace AceepSystem.Models.Help
{
public static class Virtual_Help
{
public static bool? IsVirtual(this PropertyInfo self)
{
if (self == null)
throw new ArgumentNullException("self"); bool? found = null; foreach (MethodInfo method in self.GetAccessors())
{
if (found.HasValue)
{
if (found.Value != method.IsVirtual)
return null;
}
else
{
found = method.IsVirtual;
}
} return found;
}
}
}
使用方法如下
string json = JsonConvert.SerializeObject(
list,
Formatting.Indented,
JsonForEF.GetJsonConfig<dic_attribution>()
);//转C#对象为Json数据
EF 序列化实体为Json时的循环引用问题(不用自己写实体,不用匿名类型,不用EF的上下文属性)的更多相关文章
- jackson实体转json时 为NULL不参加序列化的汇总
首先加入依赖 <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson ...
- 此类目的是防治序列化Json字符串时的循环引用问题-------最好解决方案
http://james.newtonking.com/json/help/index.html using Newtonsoft.Json;using System;using System.Col ...
- 使用 EntityFramework后把一个对象序列化成json字符串引起循环引用的问题
先看一个T4模板生成的model实体类 著作权归作者所有. 商业转载请联系作者获得授权,非商业转载请注明出处. 作者:卷猫 链接:http://anneke.cn/ArticleInfo/Detial ...
- 前后台分离开发时遇到循环引用问题"$ref"
1. 遇到的问题 { "errMsg": "", "data": { "baseinfo": { "freeT ...
- at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:142) :json转化“$ref 循环引用”的问题
原因: entity实体中存在@OneToMany,@ManyToOne注解,在转化json是产生了循环引用 报的错误 解决方法: springmvc @ResponseBody 默认的json转化用 ...
- 用JSON.stringify处理循环引用对象
通常,我们会用JSON.stringify把Javascript对象序列化成JSON格式,这在大多数情况下是够用的.但是,当你要转换的对象里存在循环引用时,问题就来了. js对象循环引用导致内存泄漏 ...
- EF中用Newtonsoft.Json引发的循环引用问题
描述: 1.双向关系表a->b b->aList 2.在查询a引用b以后 3.用Newtonsoft.Json 去tojsonstring 4.一个只有6条数据的json串 出现了一屏幕字 ...
- EntityFramework Model有外键时,Json提示循环引用 解决方法
正文之前先说两句,距离上篇博客已将近两个月,这方面的学习和探索并没有停止,而是前进道路上遇上了各种各样的问题,需要不断的整理.反思和优化,这段时间的成果,将在最近陆续整理发出来. 个人感觉国内心态太浮 ...
- EntityFramework中Json序列化的循环引用问题解决--Newtonsoft.Json
1.在使用EF时,由于数据库主外键关联,将对象进行Json序列化时会遇到循环引用的问题 //EF 中由于数据库主外键关联,对象的序列化经常出现循环引用问题 //使用.Net 自带的序列化工具,序列化出 ...
随机推荐
- SyntaxError: Non-ASCII character '\xe5' in file index.py on line 6, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
python入门,hhh 在慕课网上学习python入门,编写汉诺塔的递归调用时,代码正确.但是加上注释后编译不通过 报如下错误: SyntaxError: Non-ASCII character , ...
- ado.net 调用带参数的存储过程
String connString = "Data Source = localhost; Initial Catalog = hkjc;User ID = sa;Pwd = 123&quo ...
- 10分钟学会搭建Android开发环境 Eclipse: The import android.support cannot be resolved
10分钟学会搭建Android开发环境_隋雨辰 http://v.youku.com/v_show/id_XNTE2OTI5Njg0.html?from=s1.8-1-1.2 The import a ...
- Android设计模式系列(3)--SDK源码之单例模式
单例模式,可以说是GOF的23种设计模式中最简单的一个.这个模式相对于其他几个模式比较独立,它只负责控制自己的实例化数量单一(而不是考虑为用户产生什么样的实例),很有意思,是一个感觉上很干净的模式,本 ...
- Linux命令-文件搜索命令:whereis
主要用途:查找linu命令,而不是磁盘上的普通文件,并且能看到命令的目录和帮助文件. whereis useradd 查找命令useradd的所在位置,同时还查出来它的帮助文件所在位置 whereis ...
- Linux命令-文件处理命令:tail
tail /etc/services 查看etc目录的services文件最后10行内容(默认显示后10行内容) tail -n /etc/services 查看etc目录的services文件的后5 ...
- Android EditText 赋值与取值
//取值 String strSmsPhone=m_txtSmsPhone.getText().toString(); //赋值 m_txtSmsPhone.setText("你好" ...
- C#: 数字经纬度和度分秒经纬度间的转换
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...
- 分别用C和C++来实现一个链栈
下面通过分别用C和C++来实现一个链栈(链表实现),从中体会数据封装抽象的思想: C语言实现: C++ Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
- EF6 Code First 模式更新数据库架构
定义好实体类和上下文类 在 Package Manager Console 输入以下命令 1.Enable-Migrations 启用数据迁移功能,该命令通常会在项目根目录下生成 Migrations ...