C# Newtonsoft.Json 序列化忽略 null值
时间: 2024-06-15 17:03:54 浏览: 25
在C#中,使用Newtonsoft.Json库进行JSON序列化时,可以通过设置属性来忽略null值。具体的方法是使用JsonProperty特性,并将其NullValueHandling属性设置为NullValueHandling.Ignore。
下面是一个示例代码:
```csharp
using Newtonsoft.Json;
public class MyClass
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
MyClass obj = new MyClass
{
Name = null,
Age = 20
};
string json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
}
}
```
在上面的示例中,通过在Name属性上添加JsonProperty特性,并将NullValueHandling属性设置为NullValueHandling.Ignore,可以实现在序列化时忽略null值。当Name属性为null时,序列化后的JSON字符串中将不包含该属性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)