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.
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.
DeserializeObject can throw several unexpected exceptions (JsonReaderException is the one that is usually expected). These are: ArgumentException.
Deserialization ignores nulls in the json and doesn't update the property.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With