© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
5 replies
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}");
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
WeatherForecase
not
WeatherForecast?
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!
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

deserialize non-nullable
C#CC# / help
2y ago
✅ JsonSerializer: Won't deserialize correctly
C#CC# / help
3y ago
JsonSerializer.Deserialize will not translate number to string
C#CC# / help
3y ago