I have a class that is annotated with DataContract and DataMember attributes. Some members are marked as DataMember(IsRequired = true)
. When I serialize instances over the wire from Json.NET, and the required object members have null value, then their serialized values are missing in the output (which is apparently equivalent to being null in JSON). I'm okay with that.
I've created a sort of "echo" service which returns data sent to it as a response. So this service receives the JSON with missing members (or null members depending on how you look at it), and then sends it right back to my Json.NET client. The JSON on the wire looks the same in both directions as viewed through Fiddler (a proxy sniffer). So far so good.
When the original Json.NET sender receives the JSON response to deserialize it, the serializer throws an exception about not finding required members in the JSON payload:
Required property 'IAmRequired' not found in JSON. Path ''.
That is unfortunate, as the serializer is thus not able to deserialize data that it had previously serialized without a problem.
Short of changing the DataContract class to make the member not required (which I do not want to do for a number of reasons), is there a way to make Json.NET deserialize missing members to default values such as null?
Here is my deserialization code:
HasRequired h = null;
JObject json = response as JObject; // hand waving here
try
{
JsonSerializer ser = new JsonSerializer();
ser.MissingMemberHandling = MissingMemberHandling.Ignore; // doesn't seem to help
ser.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate; // doesn't seem to help
ser.NullValueHandling = NullValueHandling.Include; // doesn't seem to help
h = json.ToObject<HasRequired>(ser);
}
catch (Exception ex)
{
// bummer, missing required members still
}