This is following an example based on code from this question (albeit for Serialization). Is it possible to override all Required.Always
to be Required.Default
(i.e. "optional"), and allow me to deserialize an object regardless of the "required" attributes?
public class OverrideToDefaultContractResolver : DefaultContractResolver
{
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
contract.ItemRequired = Required.Default;
return contract;
}
}
public class MyClass
{
[JsonProperty("MyRequiredProperty", Required = Required.Always, NullValueHandling = NullValueHandling.Ignore)]
public string MyRequiredProperty { get; set; }
}
public static void Test()
{
var settings = new JsonSerializerSettings { ContractResolver = new OverrideToDefaultContractResolver() };
MyClass obj = JsonConvert.DeserializeObject<MyClass>(@"{""Nope"": ""Hi there""}", settings);
Console.WriteLine($"Json property: {obj.MyRequiredProperty}");
}