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 自带的序列化工具,序列化出 ...
随机推荐
- js 字符串indexof与search方法的区别
1.indexof方法 indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置. 语法: 注意:有可选的参数(即设置开始的检索位置). 2.search方法 search() 方法用 ...
- Drupal 7 driver for SQL Server and SQL Azure
Drupal 7 driver for Microsoft SQL Server database engines. It supports both SQL Server (version 2008 ...
- Android 图片压缩器
概述 Android 图片压缩器:一款高效的图片压缩器库,支持批量压缩,异步压缩.多线程多任务压缩,压缩比设置等特性. 详细 代码下载:http://www.demodashi.com/demo/12 ...
- 使用xftp连接VirtualBox中的centos6.5
首先要在windows上安装xftp软件,这个是傻瓜式操作就不说了 安装完毕之后,在centos上查看是否装了xftpd服务. [root@centos Desktop]# rpm -qa | gre ...
- [Jobdu] 题目1504:把数组排成最小的数
题目描述: 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个.例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323. 输入: 输 ...
- Message: 'geckodriver' executable needs to be in PATH. 解决方法
问题描述: 执行如下代码 # coding=utf-8 from selenium import webdriver driver = webdriver.Firefox() driver.maxim ...
- Bootstrap的js插件之折叠(collapse)
data-toggle="collapse"--指明该元素具有折叠功能: data-target--设置元素打开折叠后指向的元素链接. .collapse--用来设置元素为折叠内容 ...
- SecureCRT配置自动保存日志(实用)
点“选项”---“全局选项”--“全局选项”--“默认会话”--“编辑默认设置”--“日志文件” 在“日志文件”中输入相应的参数就能达到这一效果. 比如你的日志文件放在的D:/SecureCRT/lo ...
- 导出word功能,用html代码在word中插入分页符
<span lang=EN-US style="font-size:10.5pt;mso-bidi-font-size:12.0pt;font-family:" mce_st ...
- error: invalid use of incomplete type
一般出现这种情况都是没有将用到的头文件包含进来 我的情况是在头文件中定义了一个QMenu的指针,在源文件中使用menuBar()函数来返回一个menu指针.我在源文件中包含了文件<QtGui&g ...