Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases JsonConvert.DeserializeObject<T> actually returns null?

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.

like image 845
Enrico Massone Avatar asked Jul 20 '20 16:07

Enrico Massone


People also ask

Can JsonSerializer deserialize return null?

The JSON.Net deserializer handles this and returns null. The JsonDeserializer in RestSharp successfully deserializes the string "null" to a null object, but then inside JsonDeserializer. Map(), the second parameter, which represents dictionary of data that has been deserialized, is null.

Can JsonConvert DeserializeObject throw?

DeserializeObject can throw several unexpected exceptions (JsonReaderException is the one that is usually expected). These are: ArgumentException.

Can we deserialize null?

Deserialization ignores nulls in the json and doesn't update the property.


1 Answers

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
like image 73
CodeCaster Avatar answered Nov 15 '22 11:11

CodeCaster