Reputation: 116548
I'm using Json.Net to serialize and deserialize classes to json and back.
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: Required property
'<PropertyName>'
not found in JSON
I thought marking that property with JsonIgnore
would solve the issue, but that doesn't work.
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);
}
Upvotes: 22
Views: 36434
Reputation: 116548
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.
To ignore the property during deserialization we need to add the JsonProperty
annotation with Required = Required.Default
(which means not required).
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; }}
}
Upvotes: 33