Newtonsoft.Json 序列化 排除指定字段或只序列化指定字段
时间: 2023-12-06 13:25:23 浏览: 32
你可以使用 Newtonsoft.Json 库中的 `[JsonIgnore]` 特性来排除指定字段的序列化,或者使用 `[JsonProperty]` 特性来只序列化指定字段。
以下是使用 `[JsonIgnore]` 特性排除指定字段的示例代码:
```csharp
public class MyClass
{
public int Id { get; set; }
[JsonIgnore]
public string SecretInfo { get; set; }
public string Name { get; set; }
}
var obj = new MyClass { Id = 1, SecretInfo = "top secret", Name = "John" };
var json = JsonConvert.SerializeObject(obj);
// Output: {"Id":1,"Name":"John"}
```
以下是使用 `[JsonProperty]` 特性只序列化指定字段的示例代码:
```csharp
public class MyClass
{
public int Id { get; set; }
[JsonProperty]
public string PublicInfo { get; set; }
public string SecretInfo { get; set; }
public string Name { get; set; }
}
var obj = new MyClass { Id = 1, PublicInfo = "public", SecretInfo = "top secret", Name = "John" };
var json = JsonConvert.SerializeObject(obj);
// Output: {"Id":1,"PublicInfo":"public"}
```
在 `[JsonProperty]` 特性中可以使用 `PropertyName` 参数来指定序列化后的字段名称,例如:
```csharp
[JsonProperty(PropertyName = "public_info")]
public string PublicInfo { get; set; }
```
这样在序列化时,该字段就会以 `public_info` 作为键名。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)