Newtonsoft.Json Deserializing Empty String

Suppose I have an object similar to 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 if any of the properties is missing. However, if I pass an empty string as follows:

JsonConvert.DeserializeObject<MyObject>("")

nullreturns, but no exception is thrown. How to set up MyObjector deserializer so that a JsonExceptionappears just as if there were no required properties?

+4
source share
2 answers

Just check the null value. This is the expected behavior as there is no object in the empty line :)

var obj = JsonConvert.DeserializeObject<MyObject>("");
if (obj == null)
{
    throw new Exception();
}
+2
source

:

[JsonObject(ItemRequired = Required.Always)]
public class MyObject
{
}
+2

All Articles