默认情况下JSON.NET针对枚举类型输出对应的INT值,如果需要输出具有语义的字符串,可指定JsonConverter的值为StringEnumConverter类型。
.Deleted }; .Indented); Console.WriteLine(json); { "UserName": "零度编程", "Status": "Deleted" } 19、指定需要序列化的属性通过JsonProperty指定哪些字段应该被序列化,需要序列化则标记,不需要序列化则取消标记。
.OptIn)] public class File { //Id不需要序列化 ; } [JsonProperty] ; } [JsonProperty] ; } } File { Id = Guid.NewGuid(), Name = "xcode.pdf", Size = 50 * 1024 }; .Indented); Console.WriteLine(json); { "Name": "xcode.pdf", "Size": 51200 } 20、序列化对象时指定属性名序列化对象时,可标记属性的JsonProperty特性,并指定需要序列化为JSON时应有的属性名。
public class Videogame { [)] ; } [)] ; } } Videogame { Name = "Starcraft", ReleaseDate = new DateTime(1998, 1, 1) }; .Indented); Console.WriteLine(json); { "name": "Starcraft", "release_date": "1998-01-01T00:00:00" } 21、序列化时指定属性在JSON中的顺序 public class Person { [JsonProperty(Order = 2)] ; } [JsonProperty(Order = 1)] ; } } }; .Indented); Console.WriteLine(json); { "LastName": "编程", "FirstName": "零度" } 22、反序列化指定属性是否必须有值必须不为null在反序列化一个JSON时,可通过JsonProperty特性的Required指定反序列化行为,当反序列化行为与指定的行为不匹配时,JSON.NET将抛出异常,Required是枚举,Required.Always表示属性必须有值切不能为null,Required.AllowNull表示属性必须有值,但允许为null值。
public class Videogame { [.Always)] ; } [.AllowNull)] ; } } string json = @"{ 'Name': 'Starcraft III', 'ReleaseDate': null }"; >(json); Console.WriteLine(starcraft.Name); Starcraft III 23、通过特性指定null值忽略序列化 public class Vessel { ; } ; } [.Ignore)] ; } } }; .Indented); Console.WriteLine(json); { "Name": "Red October", "Class": "Typhoon" } 24、忽略不需要序列化的属性并不是对象所有属性都要参与序列化,我们可以使用JsonIgnore特性排除不需要序列化的属性,下面示例中的PasswordHash将被忽略。
public class Account { ; } ; } [JsonIgnore] ; } } Account { FullName = "admin", EmailAddress = "admin@xcode.me", PasswordHash = "VHdlZXQgJ1FASmFtZXNOSw==" }; .SerializeObject(account); Console.WriteLine(json); {"FullName":"admin","EmailAddress":admin@xcode.me} 25、通过特性指定属性的默认序列化值当属性没有赋值时,默认值一般是null或者0,我们可通过DefaultValue特性改变默认值,可用指定的字符替换,而不是输出null。
public class Customer { ; } [)] ; } } {"FirstName":null,"LastName":""} 26、序列化或反序列化时指定日期时间格式JSON.NET中提供一个名为JsonSerializerSettings的设置对象,可通过此对象设置很多序列化和反序列化的行为,如果要设置JSON.NET序列化输出的日期时间格式,只需要指定格式化字符串即可。默认序列化行为,日期时间格式如下:
public class Customer { ; } ; } ; } } .Now }; .Indented); Console.WriteLine(json); { "FirstName": "零度", "LastName": "编程", "CreateDate": "2015-08-24T17:19:39.0227502+08:00" }