C# 序列化JSON时忽略空值
是否可以将对象序列化为JSON,但只能将那些属性与数据一起序列化 例如:C# 序列化JSON时忽略空值,c#,json,serialization,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 =
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" }
boss对象将序列化为:
{ "id":"5", "name":"John Doe", "supervisor":"Jane Smith" }
{ "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 });
对于任何可能难以使用VB.NET的人,语法如下JsonConvert.SerializeObject(employee,Formatting.Indented,New JsonSerializerSettings with{.NullValueHandling=NullValueHandling.Ignore})或用于对象修饰声明