JsonSerializerSettings常用配置整理

1.忽略某些属性

MemberSerialization.OptIn

默认情况下,所有的成员不会被序列化,类中的成员只有标有特性JsonProperty的才会被序列化,当类的成员很多,但客户端仅仅需要一部分数据时,很有用

     [JsonObject(MemberSerialization.OptIn)]
public class TestClass
{
public int A { get; set; }
public long B { get; set; }
public string C { get; set; }
[JsonProperty]
public DateTime D { get; set; }
public TestEnum E { get; set; }
[JsonIgnore]
public TestClass F { get; set; }
public List<TestClass> G { get; set; }
public bool H { get; set; }
}
public enum TestEnum
{
TestEnum0 = ,
TestEnum1 = ,
TestEnum2 = ,
TestEnum3 = ,
}
[JsonObject(MemberSerialization.OptIn)]
public class Person
{
[JsonIgnore]
public string Name { get; set; }
[JsonProperty]
public int Age { get; set; }
public DateTime BirthDay { get; set; }
}
                 Console.WriteLine(JsonConvert.SerializeObject(new Person { Name = "test", Age = , BirthDay = new DateTime(, , ) }));
TestClass testClass = new TestClass
{
A = ,
B = ,
C = "C",
D = DateTime.Now,
E = TestEnum.TestEnum1,
F = new TestClass
{
A = ,
B = ,
C = "Cc",
D = DateTime.Now,
E = TestEnum.TestEnum2,
F = new TestClass()
},
G = new List<TestClass>
{
new TestClass
{
A=,
B=,
C="CCC",
E=TestEnum.TestEnum1,
F=new TestClass()
}
}
};
Console.WriteLine(JsonConvert.SerializeObject(testClass));

输出结果:

{"Age":18}
{"D":"2019-11-26T10:37:33.7655514+08:00"}

MemberSerialization.OptOut

默认类中所有公有成员会被序列化,如果不想被序列化,可以用特性JsonIgnore

将上面的代码OptIn改为OptOut输出结果:

{"Age":18,"BirthDay":"2011-01-01T00:00:00"}
{"A":1,"B":2,"C":"C","D":"2019-11-26T15:49:37.9507028+08:00","E":1,"G":[{"A":111,"B":222,"C":"CCC","D":"0001-01-01T00:00:00","E":1,"G":null,"H":false}],"H":false}

2.默认值的处理

DefaultValueHandling.Ignore  序列化和反序列化时,忽略默认值

                 TestClass testClass = new TestClass
{
A = ,
B = ,
C = "C",
D = DateTime.Now,
E = TestEnum.TestEnum1,
F = new TestClass
{
A = ,
B = ,
C = "Cc",
D = DateTime.Now,
E = TestEnum.TestEnum2,
F = new TestClass()
},
G = new List<TestClass>
{
new TestClass
{
A=,
B=,
C="CCC",
E=TestEnum.TestEnum1,
F=new TestClass()
}
}
};
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.DefaultValueHandling = DefaultValueHandling.Ignore;
Console.WriteLine(JsonConvert.SerializeObject(testClass,settings));

输出结果:

{"A":1,"B":2,"C":"C","D":"2019-11-26T15:56:21.7204132+08:00","E":1,"G":[{"A":111,"B":222,"C":"CCC","E":1}]}

DefaultValueHandling.Include  序列化和反序列化时,包含默认值

将JsonSerializerSettings.DefaultValueHandling属性设为DefaultValueHandling.Include输出结果:

{"A":1,"B":2,"C":"C","D":"2019-11-26T16:21:48.5429746+08:00","E":1,"G":[{"A":111,"B":222,"C":"CCC","D":"0001-01-01T00:00:00","E":1,"G":null,"H":false}],"H":false}

DefaultValueHandling.Populate  在反序列化时,具有默认值但没有JSON的成员将被设置为其默认值。

DefaultValueHandling.IgnoreAndPopulate  在序列化对象时忽略成员值与成员默认值相同的成员,在反序列化时将成员设置为其默认值

不指定的情况下,序列化时 默认 包含-DefaultValueHandling.Include

3.空值的处理

设置JsonSerializerSettings.NullValueHandling属性

对序列化过程中所有属性生效的,想单独对某一个属性生效可以使用JsonProperty

值为NullValueHandling.Ignore时,输出结果为:

{"A":1,"B":2,"C":"C","D":"2019-11-26T16:34:21.3205145+08:00","E":1,"G":[{"A":111,"B":222,"C":"CCC","D":"0001-01-01T00:00:00","E":1,"H":false}],"H":false}

值为NullValueHandling.Include时,输出结果为:

{"A":1,"B":2,"C":"C","D":"2019-11-26T16:34:21.3205145+08:00","E":1,"G":[{"A":111,"B":222,"C":"CCC","D":"0001-01-01T00:00:00","E":1,"G":null,"H":false}],"H":false}

4.支持非公共成员

序列化时默认都是处理公共成员,如果需要处理非公共成员,就要在该成员上加特性JsonProperty

5.日期处理(DateFormatHandling)

对于Dateime类型日期的格式化,系统自带的会格式化成iso日期标准{"BirthDay":"2011-01-01T00:00:00"}

解决方案1:添加特性,指定转换格式

     public class LongDateTimeConvert: Newtonsoft.Json.Converters.IsoDateTimeConverter
{
public LongDateTimeConvert() : base()
{
base.DateTimeFormat = "yyyy-MM-dd";
}
}
//[JsonConverter(typeof(LongDateTimeConvert))]
public DateTime BirthDay { get; set; }

输出结果:{"BirthDay":"2011-01-01"}

解决方案2:指定JsonSerializerSettings.DateFormatString的值

                 JsonSerializerSettings settings = new JsonSerializerSettings();
settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
var str = JsonConvert.SerializeObject(new Person { Name = "test", Age = , BirthDay = new DateTime(, , ) }, settings);
Console.WriteLine(str);

输出结果:{"BirthDay":"2011-01-01 00:00:00"}

同时指定时以特性(即方案1)为准

6.自定义序列化的字段名称

实体中定义的属性名可能不是自己想要的名称,但是又不能更改实体定义,这个时候可以自定义序列化字段名称

[JsonProperty(PropertyName = "age")]
public int Age { get; set; }

输出结果:{"age":18}

 7.动态决定属性是否序列化

指定JsonSerializerSettings.ContractResolver的实例,继承DefaultContractResolver类,重写方法

     public class JsonContractResolver : DefaultContractResolver
{
protected IEnumerable<string> _excludedProperties;
public JsonContractResolver(IEnumerable<string> excludedProperties)
{
this._excludedProperties = excludedProperties;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return base.CreateProperties(type, memberSerialization).Where(a=>!this._excludedProperties.Contains(a.PropertyName)).ToList();
}
}
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver =new JsonContractResolver(new[] { "Sign" });
settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
var str = JsonConvert.SerializeObject(new Person { Name = "test", Age = , BirthDay = new DateTime(, , ) }, settings);
Console.WriteLine(str);

过滤属性名为Sign的字段,输出结果:{"age":18,"BirthDay":"2011-01-01T00:00:00"}

8.枚举值的自定义格式化问题

默认枚举输出的是枚举的 值 {"E":1}

在属性上加上JsonConverter(typeof(StringEnumConverter))表示将枚举值转换成对应的字符串,StringEnumConverter是Newtonsoft.Json内置的转换类型

输出结果:{"E":"TestEnum1"}

9.自定义类型转换

需要扩展类JsonConverter类

10.全局序列化设置

                 JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver =new JsonContractResolver(new[] { "Sign" });
settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
JsonConvert.DefaultSettings = () => settings;

指定JsonConvert.DefaultSettings

11.指定序列化时Key的处理方式:驼峰样式,默认样式(ContractResolver)

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

var str = JsonConvert.SerializeObject(new Person { Name = "test", Age = 18, BirthDay = new DateTime(2011, 1, 1) },Formatting.Indented);

Formatting.Indented 格式化json字符串数据,锯齿状的

输出结果:

{
"sign": false,
"age": 18,
"birthDay": "2011-01-01T00:00:00"
}

12.序列化循环 引用及处理层数

对于关联表的 对象或列表都不会序列化出来

//设置循环引用,及引用类型序列化的层数。
//注:目前在 EF core中目前不支持延迟加载,无所谓循环引用了
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Formatting = Formatting.Indented;
settings.MaxDepth = 10; //设置序列化的最大层数
settings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;//指定如何处理循环引用,None--不序列化,Error-抛出异常,Serialize--仍要序列化

本文参考文档:

https://blog.csdn.net/u011127019/article/details/72801033

Newtonsoft.Json 官方文档:https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonSerializerSettings.htm

C# Newtonsoft.Json JsonSerializerSettings配置的更多相关文章

  1. C# Newtonsoft.Json JsonSerializerSettings配置序列化操作

    https://blog.csdn.net/u011127019/article/details/72801033

  2. C# Newtonsoft.Json JsonSerializerSettings 全局序列化设置

    Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings(); JsonC ...

  3. Newtonsoft.Json 全部配置

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

  4. C# dynamic类型序列化和反序列化之Newtonsoft.Json,动态解析远端返回的jSON数据

    一.说明 1.Newtonsoft.Json 中的Linq To Json中提供了方便的json数据查询.修改等操作. 例如:JObject,JArray 2.在JObject.FromObject( ...

  5. Newtonsoft.Json[C#]

    C# Newtonsoft.Json JsonSerializerSettings配置序列化操作 https://blog.csdn.net/u011127019/article/details/72 ...

  6. C# Newtonsoft.Json JObject移除属性,在序列化时忽略

    原文 C# Newtonsoft.Json JObject移除属性,在序列化时忽略 一.针对 单个 对象移除属性,序列化时忽略处理 JObject实例的 Remove() 方法,可以在 指定序列化时移 ...

  7. C# dynamic类型序列化和反序列化之Newtonsoft.Json

    原文:C# dynamic类型序列化和反序列化之Newtonsoft.Json 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/u011127019/ ...

  8. .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程

    JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询 ...

  9. 再谈Newtonsoft.Json高级用法

    上一篇Newtonsoft.Json高级用法发布以后收到挺多回复的,本篇将分享几点挺有用的知识点和最近项目中用到的一个新点进行说明,做为对上篇文章的补充. 阅读目录 动态改变属性序列化名称 枚举值序列 ...

随机推荐

  1. MVC WebApi 返回字符串

    [HttpGet] public HttpResponseMessage GetWebConfigValue(string key) { var response = Request.CreateRe ...

  2. php踩过的那些坑(4) false,NULL,0,''详解

    一.前方有坑 php开发过程中,难免会遇到这四个值:false,null,0,’',并且也会对这四个值进行比较,然后分别进行业务代码处理.一招不慎,就会踩到坑,影响数据判断的正确性和安全性,以至于造成 ...

  3. docker镜像、docker容器导入导出命令

    一.docker镜像导入导出命令 导出命令: docker save -o <保存路径> <镜像名称:标签> docker save -o ./test.tar test:la ...

  4. ubuntu16.04 安装cuda9.0+cudnn7.0.5+tensorflow+nvidia-docker配置GPU服务

    [摘要] docker很好用,但是在GPU服务器上使用docker却比较复杂,需要一些技巧,下面将介绍一下在ubuntu16.04环境下的GPU-docker环境搭建过程. 第一步: 删除之前的nvi ...

  5. ASP.NET Core 选项模式源码学习Options Configure(一)

    前言 ASP.NET Core 后我们的配置变得更加轻量级了,在ASP.NET Core中,配置模型得到了显著的扩展和增强,应用程序配置可以存储在多环境变量配置中,appsettings.json用户 ...

  6. org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'ExtractAbstractServiceHandler' is defined

    在利用 Spring 集成 thrift 时,报错如下: javax.servlet.ServletException: Servlet.init() for servlet search-nlp-s ...

  7. [AHOI2017初中组]guide

    题目描述 农场主John最近在网上买了一辆新车,在购买汽车配件时,John不小心点了两次"提交"按钮.导致汽车上安装了两套GPS系统,更糟糕的是John在使用GPS导航时,两套系统 ...

  8. CoderForces Round526 (A~E)题解

    A. The Fair Nut and Elevator time limit per test 1 second memory limit per test 256 megabytes input ...

  9. Bless You Autocorrect!

    题目链接: https://odzkskevi.qnssl.com/0c87453efec2747f8e8a573525fd42f9?v=1533651456 题解: 这是一道Trie+BFS的题目: ...

  10. 这些C++常用内置函数你会几个??

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:Regina520  新手注意:如果你C++学的不好,可以去拿我的C+ ...