簡體   English   中英

序列化JSON時忽略空值

[英]Ignore Null Values When Serializing JSON

是否可以將對象序列化為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屬性上執行以下操作:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM