C
C#2y ago
nobody

❔ Why does the JsonSerializer.Deserialize return a nullable object

I found this following example in the docs about the deserializer:
WeatherForecast? weatherForecast =
JsonSerializer.Deserialize<WeatherForecast>(jsonString);

Console.WriteLine($"Date: {weatherForecast?.Date}");
Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}");
Console.WriteLine($"Summary: {weatherForecast?.Summary}");
WeatherForecast? weatherForecast =
JsonSerializer.Deserialize<WeatherForecast>(jsonString);

Console.WriteLine($"Date: {weatherForecast?.Date}");
Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}");
Console.WriteLine($"Summary: {weatherForecast?.Summary}");
based on the docs it looks like it would throw an exception if the json can't be deserialized. The type, for deserialization, in this case is WeatherForecase not WeatherForecast? . Why does it return nullable<..>? Is there a way to make it return the acutal instance or just throw an error? I want to avoid many (maybe unnecessary) null checks? Thx!
4 Replies
Jimmacle
Jimmacle2y ago
because you can deserialize the string null
ero
ero2y ago
yeah, the literal contents
null
null
is a valid json object so if the input contains only that, then the deserialized object will also be null
nobody
nobodyOP2y ago
ah I see, makes sense - thank you guys
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server