Stmated
Stmated

Reputation: 495

DataMemberAttribute.IsRequired is used even though NullValueHandling is Ignore

I am having an issue where a dependency I am using has set

[DataMemberAttribute(IsRequired = true)]

But it is not sending along a value for it from one point to another.

It works for them because they are using ServiceStack.Text which does not care about DataMemberAttribute.

But I am using Json.net, which does check for this attribute and subsequently fails.

(The support of the dependency I am talking about has admitted that they were at fault with setting it as required. A fix might come some day. But that's too long a wait.)

It does not even work if I create a new serializer setting such as:

new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };

The property is still set as Required.AllowNull in the method SetPropertySettingsFromAttributes() in DefaultContractResolver.cs.

The serializer settings is never checked for in that method nor in JsonSerializerInternalReader.EndObject() where this is thrown:

"Required property '...' not found in JSON."

So:

Thank you in advance!

Upvotes: 0

Views: 254

Answers (1)

Stmated
Stmated

Reputation: 495

I solved the issue by overriding the CreateProperty method of DefaultContractResolver and wrote code like so:

protected override JsonProperty CreateProperty(MemberInfo m, MemberSerialization s)
{
    var property = base.CreateProperty(m, s);
    property.Required = Required.Default;
    return property;
}

Not the most elegant of solutions... but it works, and allows me to ignore any and all required checks. This might not be the most optimal solution but is enough for my needs.

Upvotes: 2

Related Questions