16、通过ContractResolver指定属性名首字母小写,通常,在.NET中属性采用PascalCase规则(首字母大写),在JavaScript中属性名使用CamelCase规则(首字母小写),我们希望序列化后的JSON字符串符合CamelCase规则,JSON.NET提供的ContractResolver可以设置属性名小写序列化
public class User { public string Name { set; get; } public int Age { set; get; } } User person = , Age =52 }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(person, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }); Console.WriteLine(json);执行结果:
17、JSON.NET中通过特性序列化枚举类型
public enum ProductStatus { NotConfirmed, Active, Deleted } public class Product { public string Name { get; set; } [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public ProductStatus Status { get; set; } } Product user = , Status = ProductStatus.Deleted }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(user, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);执行结果:
18、指定需要序列化的属性
[Newtonsoft.Json.JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)] public class Categroy { Guid Id { get; set; } [Newtonsoft.Json.JsonProperty] public string Name { get; set; } [Newtonsoft.Json.JsonProperty] public int Size { get; set; } } Categroy categroy = new Categroy { Id = Guid.NewGuid(), Name = , Size = 52 }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(categroy, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);执行结果:
19、序列化对象时指定属性名
public class Videogame { [Newtonsoft.Json.JsonProperty()] public string Name { get; set; } [Newtonsoft.Json.JsonProperty()] public DateTime ReleaseDate { get; set; } } Videogame starcraft = new Videogame { Name = , ReleaseDate = DateTime.Now }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(starcraft, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);执行结果:
20、序列化时指定属性在JSON中的顺序
public class Personl { [Newtonsoft.Json.JsonProperty(Order = 2)] public string FirstName { get; set; } [Newtonsoft.Json.JsonProperty(Order = 1)] public string LastName { get; set; } } Personl person = , LastName = }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(person, Newtonsoft.Json.Formatting.Indented); Console.WriteLine(json);执行结果:
21、反序列化指定属性是否必须有值必须不为null,在反序列化一个JSON时,可通过JsonProperty特性的Required指定反序列化行为,当反序列化行为与指定的行为不匹配时,JSON.NET将抛出异常,Required是枚举,Required.Always表示属性必须有值切不能为null,Required.AllowNull表示属性必须有值,但允许为null值。
public class Order { [Newtonsoft.Json.JsonProperty(Required = Newtonsoft.Json.Required.Always)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty(Required = Newtonsoft.Json.Required.AllowNull)] public DateTime? ReleaseDate { get; set; } } string json = @"{ 'Name': '促销订单', 'ReleaseDate': null }"; Order order = Newtonsoft.Json.JsonConvert.DeserializeObject<Order>(json); Console.WriteLine(order.Name); Console.WriteLine(order.ReleaseDate);执行结果: