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

用匿名类型也可以。

设置上下文方法如下:

(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. Python continue

    continue继续循环在循环过程中,可以用break退出当前循环,还可以用continue跳过后续循环代码,继续下一次循环.假设我们已经写好了利用for循环计算平均分的代码: L = [75, 98 ...

  2. Android源代码目录结构(转)

    https://android.googlesource.com/ Android 2.2 |-- Makefile |-- bionic               (bionic C库) |-- ...

  3. jquery remove()不兼容问题解决方案

      jquery remove()不兼容问题解决方案 CreationTime--2018年7月27日10点19分 Author:Marydon 1.情景展示 点击关闭,将这个div移除掉 源码展示 ...

  4. python --curl重定向到文件范例

      import sys import os import subprocess import time start = time.time() old=sys.stdout f=open('test ...

  5. 摘:C#压缩文件

    [[[[C#压缩文件]]]] 方法1: //[filepath想要压缩文件的地址] //[zippath输出压缩文件的地址] private void GetFileToZip(string file ...

  6. some nets were not able to be matched

    原因是:PCB画好之后再次更改原理图,将更改后的原理图更新至PCB的时候会导致原理图中新生成的网络和PCB中原有的网络名不匹配 解决办法:PCB---设计----网络表---编辑网络,把PCB中不匹配 ...

  7. jQuery knowledge

    I have used jquery for many years, but didn't list the problem I ever meeting, so here is a list of ...

  8. Python操作redis系列以 哈希(Hash)命令详解(四)

    # -*- coding: utf-8 -*- import redis #这个redis不能用,请根据自己的需要修改 r =redis.Redis(host=") 1. Hset 命令用于 ...

  9. spring in action 8.1 使用Spring web flow

    一.说明 Spring Web Flow是spring MVC的扩展,它支持基于流程的应用程序,他将流程的定义和实现流程行为的类和视图分离开来. 1.1 spring中配置web flow,目前需要在 ...

  10. JVM虚拟机(五):JDK8内存模型—消失的PermGen

    一.JVM 内存模型 根据 JVM 规范,JVM 内存共分为虚拟机栈.堆.方法区.程序计数器.本地方法栈五个部分. 1.虚拟机栈: 每个线程有一个私有的栈,随着线程的创建而创建.栈里面存着的是一种叫“ ...