![](https://img.haomeiwen.com/i5650826/af3c545289293401.png)
官网:https://www.newtonsoft.com/json/help/html/N_Newtonsoft_Json.htm
1,序列化、反序列化
序列化DataTable:JsonConvert.SerializeObject(DataTable);
反序列化DataTable:JsonConvert.DeserializeObject<DataTable>(json);
2,忽略属性
Json.Net序列化的模式分为:OptOut(JsonIgnore)、OptIn(JsonProperty)
OptOut序列化出的时候,忽略某些属性,默认全部成员序列化
OptIn序列化入的时候,只对设置了该特性的属性进行序列化,默认全部不序列化
![](https://img.haomeiwen.com/i5650826/f4a2a57fc9f200a5.png)
![](https://img.haomeiwen.com/i5650826/bf3e7bdd16a185fd.png)
3,默认值处理
序列化时想忽略默认值属性,通过JsonSerializerSettings.DefaultValueHandling设置,该值为枚举值
序列化和反序列化时,忽略默认值使用:DefaultValueHandling.Ignore
序列化和反序列化时,包含默认值使用:DefaultValueHandling.Include
![](https://img.haomeiwen.com/i5650826/476816b48240c216.png)
4,空值的处理
序列化时需要忽略值为null的属性,可以通过JsonSerializerSettings.NullValueHandling来确定,另外通过JsonSerializerSettings设置属性时对序列化过程中所有的属性生效,想单独对某一个属性生效可以使用JsonProperty
![](https://img.haomeiwen.com/i5650826/4bb54240283b220d.png)
![](https://img.haomeiwen.com/i5650826/fd0c688a4da89a5b.png)
5,日期处理
实际使用过程中大多数使用的可能是yyyy-MM-dd 或者yyyy-MM-dd HH:mm:ss两种格式的日期,解决办法是可以将DateTime类型改成string类型自己格式化好,然后在序列化
Json.Net提供了IsoDateTimeConverter日期转换这个类,可以通过JsnConverter实现相应的日期转换:
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime Birthday { get; set; }
![](https://img.haomeiwen.com/i5650826/c89c91b091a99d2b.png)
6,支持非公共成员
序列化时默认都是处理公共成员,如果需要处理非公共成员,就要在该成员上加特性"JsonProperty"
[JsonProperty]
private int Height { get; set; }
7,自定义序列化的字段名称
实体中定义的属性名可能不是自己想要的名称,但是又不能更改实体定义,这个时候可以自定义序列化字段名称。
[JsonProperty(PropertyName = "CName")]
public string Name { get; set; }
8,全局序列化设置
Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
{
//日期类型默认格式化处理
setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//空值处理
setting.NullValueHandling = NullValueHandling.Ignore;
//高级用法九中的Bool类型转换 设置
setting.Converters.Add(new BoolConvert("是,否"));
return setting;
});
网友评论