C# with Newtonsoft.Json 13.0.2. I am deserializing a JSON string as such
var car = JsonConvert.DeserializeObject<Car>(resp);
where resp looks like this:
{
"perf": {
"perfRef": null,
"perfTest": {
"value": 1.2,
"unit": "percent"
}
}
}
My class looks like this:
public partial class perf
{
[Newtonsoft.Json.JsonProperty("perfRef", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public PerfRef perfRef { get; set; }
[Newtonsoft.Json.JsonProperty("perfTest", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public PerfTest perfTest { get; set; }
}
But I keep getting an exception
Newtonsoft.Json.JsonSerializationException: Required property 'perfRef' expects a non-null value. Path 'perf'
I don’t get why this is happening. I thought the NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
would override any ‘Required’ option. Am I just misinterpreting how the decorators work?
2
Answers
you have
Required
which means you cannot have a null value for theperfRef
property.
there are ways to solve this.
either remove
Required
or provide the value to this property or set the Required attribute toAllowNull
orDefault
.Note:
NullValueHandling
Ignore means that null values will be ignored when serializing and deserializing JSON.Could it be that the cause is that the json-string is wrapped with
{"Perf": {...}}
and you need an additional class to deserialize it.My sample array
[...]
has two json-strings. Both contain the same object{...}
{"Perf": {...}}
like your sampleYou can deserialize the first json string
json[0] = {"Perf": {"perfRef":null, "perfTest":{"value":"1.2","unit":"percent"}}}
using a class that acts as a wrapper (hereJsonResponse
):If the json-string would not be wrapped then there is no need for a wrapper class
This is a lingpad-program that deserializes both json strings:
The result of the deserialized object
JsonResponse
andPerf
are on the right side.