Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft.Json Deserializing Empty string

Tags:

json

c#

json.net

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?

like image 988
Christian Andersson Avatar asked Sep 04 '14 12:09

Christian Andersson


2 Answers

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();
}
like image 113
Eldar Dordzhiev Avatar answered Oct 07 '22 20:10

Eldar Dordzhiev


You need to decorate your class like this:

[JsonObject(ItemRequired = Required.Always)]
public class MyObject
{
}
like image 44
Radenko Zec Avatar answered Oct 07 '22 20:10

Radenko Zec