C#C
C#3y ago
florent

❔ 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}");


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!
Was this page helpful?