2014-05-10 116 views
0

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

Employee对象将被序列化为:

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

老板对象将被序列化为:

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

谢谢!

回答

3

你可以做你的JSON性质是这样的:

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

或者当你序列化,你可以忽略空值。

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

对于任何人谁可能很难得到这个与VB.NET的语法如下JsonConvert.SerializeObject(员工,Formatting.Indented,新JsonSerializerSettings随着{.NullValueHandling = NullValueHandling.Ignore})工作** * *或为对象装饰声明使用** ** – Destek