序列化JSON时忽略空值

时间:2014-05-10 04:12:17

标签: c# json serialization

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

谢谢!

1 个答案:

答案 0 :(得分:4)

您可以在JSON属性上执行以下操作:

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

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

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