Ignore a property when deserializing using Json.Net with ItemRequired = Required.Always(使用带有 ItemRequired = Required.Always 的 Json.Net 反序列化时忽略属性)
问题描述
我正在使用 Json.Net 将类序列化和反序列化为 json 并返回.
I'm using Json.Net to serialize and deserialize classes to json and back.
我向标有 [JsonObject(ItemRequired = Required.Always)](或 Required.Always)的类添加了一个新的 get-only 属性.这将导致以下 JsonSerializationException:
I added to a class marked with [JsonObject(ItemRequired = Required.Always)] (or Required.Always) a new get-only property. That results in the following JsonSerializationException:
Newtonsoft.Json.JsonSerializationException:在 JSON 中找不到必需的属性 '<PropertyName>'
Newtonsoft.Json.JsonSerializationException: Required property
'<PropertyName>'not found in JSON
我认为用 JsonIgnore 标记该属性可以解决问题,但这不起作用.
I thought marking that property with JsonIgnore would solve the issue, but that doesn't work.
我如何告诉 Json.Net 这个属性应该被忽略?
How can I tell Json.Net that this property should be ignored?
这是重现问题的最小示例:
Here's a minimal example reproducing the issue:
[JsonObject(ItemRequired = Required.Always)]
public class Hamster
{
public string FirstName { get; set; }
public string LastName { get; set; }
[JsonIgnore]
public string FullName { get { return FirstName + LastName; }}
}
private static void Main()
{
var hamster = new Hamster {FirstName = "Bar", LastName = "Arnon"};
var serializeObject = JsonConvert.SerializeObject(hamster);
var deserializeObject = JsonConvert.DeserializeObject<Hamster>(serializeObject);
}
推荐答案
显然 JsonIgnore 在这种情况下只会控制序列化.JsonIgnore 需要指定 FullName 属性不应序列化为 json 表示形式.
Evidently JsonIgnore will only control the serialization in this case. JsonIgnore is required to specify that the FullName property should not be serialized to the json representation.
要在反序列化过程中忽略该属性,我们需要添加 JsonProperty 注释和 Required = Required.Default(表示不需要).
To ignore the property during deserialization we need to add the JsonProperty annotation with Required = Required.Default (which means not required).
所以,这是避免JsonSerializationException的方法:
So, this is how to avoid the JsonSerializationException:
[JsonObject(ItemRequired = Required.Always)]
public class Hamster
{
public string FirstName { get; set; }
public string LastName { get; set; }
[JsonIgnore]
[JsonProperty(Required = Required.Default)]
public string FullName { get { return FirstName + LastName; }}
}
这篇关于使用带有 ItemRequired = Required.Always 的 Json.Net 反序列化时忽略属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用带有 ItemRequired = Required.Always 的 Json.Net 反序列化时忽略属性
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
