序列化 JSON 时忽略空值

问题描述 投票:0回答:2

是否可以将对象序列化为 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" }

谢谢!

c# json serialization
2个回答
47
投票

您可以对 JSON 属性执行类似的操作:

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

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

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

0
投票

对于那些不想使用

Newtonsoft.Json
套餐而想使用
System.Text.Json.Serialization
套餐的人,您也可以使用这个:

[JsonPropertyName("foo")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Foo { get; set; }

JsonIgnoreCondition 文档

© www.soinside.com 2019 - 2024. All rights reserved.