As shown in the original JSON proposal, the text null
is perfectly well-formed JSON:
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
This is further clarified in RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format which states that a well-formed JSON text need be nothing more than a single primitive value including null
:
A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names [false, true and null].
A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array. Implementations that generate only objects or arrays where a JSON text is called for will be interoperable in the sense that all implementations will accept these as conforming JSON texts.
Since null
is a well-formed JSON text according to this most recent JSON RFC, JsonSerializer
will not throw when deserializing it to a reference type or nullable value type, and will instead just return a null value:
object? obj1 = JsonSerializer.Deserialize<object>("null"); // Does not throw; explicitly typed for clarity.
Assert.IsNull(obj1); // Passes
var array = JsonSerializer.Deserialize<int []>("null"); // Does not throw;
Assert.IsNull(array); // Passes
var nullable = JsonSerializer.Deserialize<int?>("null"); // Does not throw;
Assert.IsNull(nullable); // Passes
Conversely the following generates a compiler warning:
#nullable enable
object obj2 = JsonSerializer.Deserialize<object>("null"); // Compiler warning: Converting null literal or possible value to non-nullable type;
And the following throws, since an int
is a non-nullable value type to which null
cannot be assigned:
var i = JsonSerializer.Deserialize<int>("null"); // Throws, since int is a non-nullable value type.
If you want to an exception to be thrown when deserializing the JSON text null
, you could add the following extension method:
public static class ObjectExtensions
{
public static T ThrowOnNull<T>(this T? value) where T : class => value ?? throw new ArgumentNullException();
}
And do:
var value = JsonSerializer.Deserialize<TValue>(json).ThrowOnNull();
Demo fiddle here.
null
is a perfectly valid JSON value according to the standard, so if you just doJsonSerializer.Deserialize<object>("null")
thennull
is returned, see dotnetfiddle.net/WTHbdo.