Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 序列化JSON时忽略空值_C#_Json_Serialization - Fatal编程技术网

C# 序列化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 =

是否可以将对象序列化为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" }
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})或用于对象修饰声明