CodexBloom - Programming Q&A Platform

C# - implementing Custom Collection Serialization Using JsonSerializer: Missing Properties

๐Ÿ‘€ Views: 55 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-14
c# json serialization C#

I've spent hours debugging this and I need help solving I'm working with an scenario with serializing a custom collection in C# using `System.Text.Json.JsonSerializer`. I have a collection of a custom class that includes properties which are sometimes null, and I expect those properties to be serialized even if they are null. However, they are not appearing in the resulting JSON string. Hereโ€™s a simplified version of the code Iโ€™m using: ```csharp public class Item { public string Name { get; set; } public string Description { get; set; } } public class ItemCollection { public List<Item> Items { get; set; } = new List<Item>(); } var collection = new ItemCollection(); collection.Items.Add(new Item { Name = "Item1", Description = null }); string json = JsonSerializer.Serialize(collection); Console.WriteLine(json); ``` When I run this, the output is: ``` {"Items":[{"Name":"Item1"}]} ``` As you can see, the `Description` property is missing from the JSON output, and I want it to include `"Description":null`. I've tried using `[JsonPropertyName]` attributes and setting `DefaultIgnoreCondition` to `JsonIgnoreCondition.WhenWritingNull`, but those havenโ€™t resolved the scenario. Is there a way to configure the serializer to include null properties in the JSON output? I'm using .NET 5.0 for this project. Any insights would be greatly appreciated! This is part of a larger API I'm building. Any ideas what could be causing this? What's the best practice here? I recently upgraded to C# 3.10. What are your experiences with this? I'm working in a Ubuntu 20.04 environment. Any pointers in the right direction?