CodexBloom - Programming Q&A Platform

Unexpected NullReferenceException When Accessing Properties of Deserialized JSON Object in C# 10

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
c# json deserialization dotnet-6 C#

I'm integrating two systems and I'm relatively new to this, so bear with me. I'm working with a `NullReferenceException` when I try to access properties of an object that I deserialize from JSON using System.Text.Json in .NET 6. The JSON structure I receive from the API looks like this: ```json { "userId": 1, "userName": "john_doe", "userDetails": { "email": "john@example.com", "age": null } } ``` Here's the C# class I defined for deserialization: ```csharp public class User { public int UserId { get; set; } public string UserName { get; set; } public UserDetails UserDetails { get; set; } } public class UserDetails { public string Email { get; set; } public int? Age { get; set; } } ``` And this is how I deserialize the JSON response: ```csharp var jsonString = await response.Content.ReadAsStringAsync(); var user = JsonSerializer.Deserialize<User>(jsonString); ``` After deserialization, when I try to access `user.UserDetails.Email`, I consistently get a `NullReferenceException`. I've verified that the JSON string is valid and correctly formatted. I also checked if `user` is null after deserialization, which it isn't. However, it seems that `UserDetails` is null, and that's why I'm getting the exception when I try to access its properties. I've tried adding null checks, but I want to understand why this is happening in the first place. Has anyone faced a similar scenario or could point out what might be going wrong here? This issue appeared after updating to C# latest. I appreciate any insights! I've been using C# for about a year now.