4
votes

I'm working with .NET core 3.1, C#8 and nullable reference types enabled.

From the class library I'm writing, I'm referencing the version 12.0.3 of the NewtonsoftJson package.

I noticed that by calling JsonConvert.DeserializeObject<T> I can get a null reference (Visual Studio analyzers detect a possible dereferencing of a null reference).

Notice that I'm calling the overload which takes a string and an instance of JsonSerializerSettings. I'm only using the JsonSerializerSettings in order to handle the possible deserialization errors (via the Error property).

The github source code confirms that the overload I'm calling can possible return a null reference, via the MaybeNull attribute: take a look here for a confirmation.

My question is: in which cases newtonsoft JSON returns a null reference when deserializing a JSON string to a .NET type ?

Usually it returns an object of the given type populated or having its properties at the default value for their type, I have never encountered a case where null is returned instead.

1

1 Answers

6
votes

Since the JSON literal null is valid JSON, you can reproduce this as follows:

var o = JsonConvert.DeserializeObject<object>("null");
Console.WriteLine(o == null); // True