Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the result of JsonSerializer.Deserialize ever be null?

Tags:

json

c#

The return type shown in the docs for the JsonSerializer.Deserialize method all show the return type as nullable.

If you look at the deserialisation examples in the MS docs, you see that they are inconsistent, in that the first and third specify the return type as nullable...

WeatherForecast? weatherForecast = 
  JsonSerializer.Deserialize<WeatherForecast>(jsonString);

...whereas the second example misses off the ?, meaning it's non-nullable.

By experimenting, it seems that as long as you supply valid JSON (otherwise you get an exception), then the return value is always a non-null object of the specified type. If the property names don't match, then the returned object will have default values for those properties, but you never get a null reference - or at least, I couldn't find a way.

Anyone able to clarify? Is there a situation in which the method can return null, without throwing an exception? If not, why are the return types specified as nullable?

Thanks

like image 322
Avrohom Yisroel Avatar asked Sep 03 '25 04:09

Avrohom Yisroel


1 Answers

Yes, parsing valid JSON "null" with a JSON serializer have to return null.

WeatherForecast? weatherForecast = 
  JsonSerializer.Deserialize<WeatherForecast>("null");

Note that other valid JSON strings like "123", "\"bob\"", "[]" should cause an exception because none of them represent a valid object.

like image 110
Alexei Levenkov Avatar answered Sep 04 '25 19:09

Alexei Levenkov