通过枚举NullValueHandling.Ignore,在使用Json.NET序列化对象为Json字符串时,可以忽略为null的属性,如下代码所示:
using Newtonsoft.Json;namespace Net8JsonNullValueDemo {class People{public required string Name{get;set;}public int? Age{get;set;}public string? Desciption{get;set;}public decimal? Salary{get;set;}}internal class Program{static void Main(string[] args){//构造一个People对象,Desciption和Salary属性为nullPeople people = new People(){Name = "王大锤, Jack Wang",Age = 16};//默认情况下,Json.NET会将为null的属性也序列化到Json字符串中string jsonWithNullValues = JsonConvert.SerializeObject(people, Formatting.Indented);Console.WriteLine(jsonWithNullValues);Console.WriteLine();Console.WriteLine();//通过声明NullValueHandling.Ignore枚举,Json.NET会忽略掉为null的属性,序列化后的Json字符串中只有非null的属性jsonWithNullValues = JsonConvert.SerializeObject(people, Formatting.Indented, new JsonSerializerSettings(){NullValueHandling = NullValueHandling.Ignore});Console.WriteLine(jsonWithNullValues);Console.WriteLine();Console.WriteLine();Console.WriteLine("Press any key to end...");Console.ReadLine();}} }
运行上面的代码,结果如下所示:
{"Name": "王大锤, Jack Wang","Age": 16,"Desciption": null,"Salary": null }{"Name": "王大锤, Jack Wang","Age": 16 }Press any key to end...
可以参考下面这篇Json.NET的官方文档:
NullValueHandling setting