Here is what I have got till now. Thanks to Brian Rodgers:
public class JsonSerializeTest
{
[Fact]
public void deserialize_test()
{
var settings = new JsonSerializerSettings { ContractResolver = new CustomContractResolver() };
var jsonString = "{\"PropertyA\":\"Test\",\"PropertyB\":null}";
var jsonObject = JsonConvert.DeserializeObject<NoConfigModel>(jsonString, settings);
Assert.NotNull(jsonObject);
}
}
public class NoConfigModel
{
public string PropertyA { get; set; }
public int PropertyB { get; set; }
public bool PropertyC { get; set; }
}
class CustomContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
property.ShouldDeserialize = instance =>
{
try
{
PropertyInfo prop = (PropertyInfo)member;
if (prop.CanRead)
{
var value = prop.GetValue(instance, null);// getting default value(0) here instead of null for PropertyB
return value != null;
}
}
catch
{
}
return false;
};
return property;
}
}
My Problem:
Need to set default value to Not Nullable fields instead of Exception or whole object being null. Having missing value is not a problem (gives default value by DefaultContractResolver
), but when a not nullable value is explicitly set as null in json then this gives exception.
My code above is close but not close enough. I think I need to find a way to know that the value is actually null from json and set ShouldDeserialize =false
for those cases.