2014-05-10 170 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