在序列化JSON时忽略空值

本文关键字:空值 序列化 JSON | 更新日期: 2023-09-27 18:02:35

是否有可能将对象序列化为JSON,但只有那些具有数据的属性?

例如:

public class Employee
{
   [JsonProperty(PropertyName = "name")]
   public string Name { get; set; }
   [JsonProperty(PropertyName = "id")]
   public int EmployeeId { get; set; }
   [JsonProperty(PropertyName = "supervisor")]
   public string Supervisor { get; set; }
}
var employee = new Employee { Name = "John Doe", EmployeeId = 5, Supervisor = "Jane Smith" };
var boss = new Employee { Name = "Jane Smith", EmployeeId = 1 };

雇员对象将被序列化为:

 { "id":"5", "name":"John Doe", "supervisor":"Jane Smith" }

boss对象将被序列化为:

 { "id":"1", "name":"Jane Smith" }

谢谢!

在序列化JSON时忽略空值

您可以在JSON属性中这样做:

[JsonProperty("property_name", NullValueHandling = NullValueHandling.Ignore)]

或者,您可以在序列化时忽略空值。

string json = JsonConvert.SerializeObject(employee, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });