Home > Blockchain >  Can the result of JsonSerializer.Deserialize ever be null?
Can the result of JsonSerializer.Deserialize ever be null?

Time:05-18

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

CodePudding user response:

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.

  • Related