Hello World!

Newtonsoft.Json 全部配置

需要在序列化时候,忽略掉某些字段,对Newtonsoft.Json进行全局配置,如下:

1. 自定 ContractResolver

  public class MyContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            if (!typeof(EntityBase).IsAssignableFrom(type))
            {
                return base.CreateProperties(type, memberSerialization);
            }
            IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
            foreach (var prop in props)
            {
                if (prop.DeclaringType.FullName != null && prop.DeclaringType.FullName.StartsWith("PWMIS.DataMap.Entity.EntityBase"))
                {
                    prop.Ignored = true;
                }
            }
            return props;
        }
    }

  2. 应用程序启动的时候对JsonConvert进行默认配置:

    JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                Formatting = Formatting.None,
                ContractResolver = new MyContractResolver()
            };


            JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
            {
                //日期类型默认格式化处理
                setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";

                //空值处理
                setting.NullValueHandling = NullValueHandling.Ignore;

                return setting;
            });

  

posted @ 2018-03-01 17:42  世界万物  阅读(514)  评论(0编辑  收藏  举报
Bye World!