22、通过特性指定null值忽略序列化
public class Vessel { public string Name { get; set; } [Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public DateTime? LaunchDate { get; set; } } Vessel vessel = }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(vessel, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);执行结果:
23、忽略不需要序列化的属性,并不是对象所有属性都要参与序列化,我们可以使用JsonIgnore特性排除不需要序列化的属性,下面示例中的PasswordHash将被忽略。
public class Accounts { public string FullName { get; set; } public string EmailAddress { get; set; } [Newtonsoft.Json.JsonIgnore] public string PasswordHash { get; set; } } Accounts account = new Accounts { FullName = , EmailAddress = , PasswordHash = }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(account); Console.WriteLine(json);执行结果:
24、序列化或反序列化时指定日期时间格式,JSON.NET中提供一个名为JsonSerializerSettings的设置对象,可通过此对象设置很多序列化和反序列化的行为,如果要设置JSON.NET序列化输出的日期时间格式,只需要指定格式化字符串即可。通过JsonSerializerSettings的DateFormatString属性指定日期时间格式:
public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public DateTime CreateDate { get; set; } } Customer custom = , LastName = , CreateDate = DateTime.Now }; Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatString = , Formatting = Newtonsoft.Json.Formatting.Indented }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(custom, settings); Console.WriteLine(json);执行结果:
加入asp.net QQ群(465693471) 点击加群,共同交流进度!