Lets say I have a object looking like this:
public class MyObject
{
[JsonProperty(Required = Required.Always)]
public string Prop1 { get; set; }
[JsonProperty(Required = Required.Always)]
public string Prop2 { get; set; }
}
Now if I try to deserialize a string using JsonConvert
an exception is thrown when either of the properties is missing.
However, If I pass an empty string like this:
JsonConvert.DeserializeObject<MyObject>("")
null
is returned but no exception is thrown. How can I configure MyObject
or the deserializer so that a JsonException
is thrown just like when any of the required properties are missing?
Just check for null. It's an expected behavior, as there is no object defined in an empty string :)
var obj = JsonConvert.DeserializeObject<MyObject>("");
if (obj == null)
{
throw new Exception();
}
You need to decorate your class like this:
[JsonObject(ItemRequired = Required.Always)]
public class MyObject
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With