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

用匿名类型也可以。

设置上下文方法如下:

(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. Vertica7 Native Connection Load Balance

    原文链接:Vertica7 Native Connection Load Balance 在Vertica7曾经的版本号中,Vertica是通过Linux的Virtual IP来实现连接的负载均衡的, ...

  2. MVC4 WebApi开发中如果想支持Session请做好如下几个方面的问题

    1.在WebApiConfig中建立建立HttpControllerHandler和HttpControllerRouteHandler 并覆写它 public class SessionRouteH ...

  3. Google C++ Coding Style 学习笔记

    写在前面:最新公司马上就要开始开发一款视觉产品,工程量较大,且需要对客户提供可以二次开 发的SDK,整个项目用C++编写. 这就对代码质量提出了非常高的要求,同时,如何设计出优雅稳定的API也是相当大 ...

  4. 定制ADempiere(1)- 会议记录

    本文是<ADempiere 3.6 Cookbook>一书的实例笔记,详细内容请查阅该书完整内容. 1. 登录pgAdmin III,创建表c_mom: CREATE TABLE adem ...

  5. 【phpstorm】破解安装

    1.使用前修改C:\windows\system32\Driver\hosts文件,将“0.0.0.0 account.jetbrains.com”添加到hosts文件中. 2. 浏览器打开 http ...

  6. BeanUtils的介绍使用

    BeanUtils工具 在实际的开发中我们经常需要将用户的录入的数据进行封装为对象,那么如果使用反射和内省技术就会变得吃力.因此本节主要给大家讲解一个开源的操作JavaBean的一个工具即BeanUt ...

  7. centos下 安装jdk

    JDK 1.7下载地址 http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html JDK ...

  8. TCP的发送缓冲区和接收缓冲区

    TCP协议是作用是用来进行端对端数据传送的,那么就会有发送端和接收端,在操作系统有两个空间即user space和kernal space. 每个Tcp socket连接在内核中都有一个发送缓冲区和接 ...

  9. create table like 和create table select 比较

    语法: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name     [(create_definition,...)]     [table_optio ...

  10. Atitit. 悬浮窗口的实现 java swing c# .net c++ js html 的实现

    Atitit. 悬浮窗口的实现 java swing c# .net c++ js html 的实现 1. 建立悬浮窗口引用代码 1 1.1. 定义悬浮窗口,设置this主窗口引用,是为了在悬浮窗口中 ...