問題描述
我正在使用 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 反序列化時忽略屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!