自己写实体可以完美解决这个问题。(支持时间格式自定义)

用匿名类型也可以。

设置上下文方法如下:

(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的上下文属性)的更多相关文章

  1. jackson实体转json时 为NULL不参加序列化的汇总

    首先加入依赖 <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson ...

  2. 此类目的是防治序列化Json字符串时的循环引用问题-------最好解决方案

    http://james.newtonking.com/json/help/index.html using Newtonsoft.Json;using System;using System.Col ...

  3. 使用 EntityFramework后把一个对象序列化成json字符串引起循环引用的问题

    先看一个T4模板生成的model实体类 著作权归作者所有. 商业转载请联系作者获得授权,非商业转载请注明出处. 作者:卷猫 链接:http://anneke.cn/ArticleInfo/Detial ...

  4. 前后台分离开发时遇到循环引用问题"$ref"

    1. 遇到的问题 { "errMsg": "", "data": { "baseinfo": { "freeT ...

  5. at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:142) :json转化“$ref 循环引用”的问题

    原因: entity实体中存在@OneToMany,@ManyToOne注解,在转化json是产生了循环引用 报的错误 解决方法: springmvc @ResponseBody 默认的json转化用 ...

  6. 用JSON.stringify处理循环引用对象

    通常,我们会用JSON.stringify把Javascript对象序列化成JSON格式,这在大多数情况下是够用的.但是,当你要转换的对象里存在循环引用时,问题就来了. js对象循环引用导致内存泄漏 ...

  7. EF中用Newtonsoft.Json引发的循环引用问题

    描述: 1.双向关系表a->b b->aList 2.在查询a引用b以后 3.用Newtonsoft.Json 去tojsonstring 4.一个只有6条数据的json串 出现了一屏幕字 ...

  8. EntityFramework Model有外键时,Json提示循环引用 解决方法

    正文之前先说两句,距离上篇博客已将近两个月,这方面的学习和探索并没有停止,而是前进道路上遇上了各种各样的问题,需要不断的整理.反思和优化,这段时间的成果,将在最近陆续整理发出来. 个人感觉国内心态太浮 ...

  9. EntityFramework中Json序列化的循环引用问题解决--Newtonsoft.Json

    1.在使用EF时,由于数据库主外键关联,将对象进行Json序列化时会遇到循环引用的问题 //EF 中由于数据库主外键关联,对象的序列化经常出现循环引用问题 //使用.Net 自带的序列化工具,序列化出 ...

随机推荐

  1. js setTimeout和setInterval区别

    1.区别 2.示例代码 <!DOCTYPE html> <html lang="zh"> <head> <meta charset=&qu ...

  2. OJ帐号保存

    TOJ 614173971 HDU 宇智波佐助 POJ shiai ZOJ henyumen UVa henyumen Light OJ HENYUMEN bzoj henyumen ural 165 ...

  3. js 多选选择删除数据

    按了顶上的删除(多项删除) 单列复选框删除 js语句 <a href="javascript:delOne('${customer.id}')">删除</a> ...

  4. Android权限注解

    Android应用程序在使用很多功能的时候必须在Mainifest.xml中声明所需的权限,否则无法运行.下面是一个Mainifest.xml文件的例子: <?xml version=" ...

  5. 【剑指Offer面试题】 九度OJ1510:替换空格

    c/c++ 中的字符串以"\0"作为结尾符.这样每一个字符串都有一个额外字符的开销. 以下代码将造成内存越界. char str[10]; strcpy(str, "01 ...

  6. FreeMarker中的list集合前后台代码

    freemarker中的list集合前后台代码: FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页.电子邮件.配置文件.源代码等)的通用工具. 它 ...

  7. atitit.html5 vs 原生 app的区别与选择

    atitit.html5  vs 原生 app的区别与选择 1. html5的优点 1 1.1. 最大优势::在跨平台(ios苹果,android安卓等) 1 1.2. 开放性 1 1.3. 快速的更 ...

  8. android BaseAdapter getView 理解

    ListView是安卓中很经常使用的一个控件. 安卓设计使用Adapter来对ListView进行管理. 可是系统提供的Adapter无法满足一些复杂的显示情况,这个时候我们就须要使用BaseAdap ...

  9. cocos2d-x与ISO内存管理(转)

    一,IOS与图片内存 在IOS上,图片会被自动缩放到2的N次方大小.比如一张1024*1025的图片,占用的内存与一张1024*2048的图片是一致的.图片占用内存大小的计算的公式是:长*宽*4.这样 ...

  10. cookie,session,localStage,sessionStage区别

    Cookie和Session详解 1.什么是Cookie Cookie是存放在客户端浏览器的Name/Value键值对,访问服务器时,会自动传递给服务器. Cookie的生成方式有两种,服务器写入,客 ...