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 反序列化时忽略属性
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01