CodexBloom - Programming Q&A Platform

How to implement guide with serializing complex object with nullable properties in c# - getting nullreferenceexception

πŸ‘€ Views: 74 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-06
c# json serialization dotnet-6 C#

I just started working with I'm working with a `NullReferenceException` when trying to serialize a complex object that contains nullable properties using `JsonSerializer` in .NET 6. When I attempt to serialize the object, it seems like the serializer is trying to access a property of a nested object that is not initialized. Here’s a simplified version of my class structure: ```csharp public class Order { public int OrderId { get; set; } public Customer? CustomerDetails { get; set; } } public class Customer { public string Name { get; set; } public Address? ShippingAddress { get; set; } } public class Address { public string Street { get; set; } public string? City { get; set; } } ``` When I create an instance of `Order` like this: ```csharp var order = new Order { OrderId = 1, CustomerDetails = new Customer { Name = "John Doe", ShippingAddress = null // Intentionally setting to null } }; ``` And try to serialize it with: ```csharp string jsonString = JsonSerializer.Serialize(order); ``` I get the following behavior: ``` System.NullReferenceException: Object reference not set to an instance of an object. ``` I’ve tried to ensure all properties are initialized and handled nullable types correctly, but the behavior continues. I’ve also checked the `JsonSerializerOptions` to see if there's any setting I might have missed, but everything seems fine. Is there a way to handle this situation, or is there a specific setting I need to use for nullable properties in `JsonSerializer`? Any pointers would be greatly appreciated! Any suggestions would be helpful.