C# Newtonsoft.Json 如果是null 忽略
时间: 2024-03-13 20:40:43 浏览: 22
C# Newtonsoft.Json一个常用的 JSON 序列化和反序列化库。它提供了一种简方便的方式来处理 JSON 数据。当使用 Newtonsoft.Json 进行序列化时,可以通过设置属性 `NullValueHandling` 来控制对于 null 值的处理方式。
如果设置 `NullValueHandling` 为 `NullValueHandling.Ignore`,则在序列化过程中,如果属性的值为 null,那么该属性将被忽略,不会包含在生成的 JSON 字符串中。
以下是一个示例代码:
```csharp
using Newtonsoft.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
public class Program
{
public static void Main()
{
var person = new Person
{
Name = "John",
Age = 30,
Address = null
};
var json = JsonConvert.SerializeObject(person, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Console.WriteLine(json);
}
}
```
在上述示例中,由于 `Address` 属性的值为 null,所以在序列化时会被忽略,生成的 JSON 字符串只包含 `Name` 和 `Age` 属性。