Search code examples
c#.netjson.netjson-deserialization

Under what circumstances will JsonConvert.DeserializeObject return null


The signature of the method JsonConvert.DeserializeObject() method in Newtonsoft.Json (Json.NET) is:

public static object? DeserializeObject(string value)

Source code here.

The method (and all its overloads) return a nullable object. I want to know under what circumstances will it return null? I was always under the impression that this method either throws Newtonsoft.Json.JsonException in case of unsuccessful deserialization or a properly constructed object in case of successful deserialization. The official documentation doesn't help in explaining the nullability either.

One possible circumstance might be that the exception was handled by a custom handler. Is there any other case that the method can return null?

var obj = JsonConvert.DeserializeObject<MyObject>("invalid json", new JsonSerializerSettings
{
    Error = (sender, args) => args.ErrorContext.Handled = true
});
// obj is null here?

Solution

  • As mentioned by @Lasse V. Karlsen in the comments, the following code will return null

    JsonConvert.DeserializeObject<SomeClass>("")
    // or
    JsonConvert.DeserializeObject<SomeClass>("null")
    

    The same applies to the value of any property

    JsonConvert.DeserializeObject<SomeClass>("{someProp : null}")
    

    Note that an actual null string will throw an ArgumentNullException

    JsonConvert.DeserializeObject<SomeClass>(null)