Reputation: 151
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?
Upvotes: 15
Views: 17030
Reputation: 7669
You need to decorate your class like this:
[JsonObject(ItemRequired = Required.Always)]
public class MyObject
{
}
Upvotes: 1
Reputation: 5135
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();
}
Upvotes: 7