文章出處

自己寫實體可以完美解決這個問題。(支持時間格式自定義)

用匿名類型也可以。

設置上下文方法如下:

(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數據

 


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()