CodexBloom - Programming Q&A Platform

Handling JSON Serialization Issues with ASP.NET Core 5 and System.Text.Json

👀 Views: 1600 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
asp.net-core json serialization system.text.json csharp

I'm currently developing an ASP.NET Core 5 web API that needs to serialize a complex object into JSON. However, I'm facing issues with certain properties not being serialized as expected. Specifically, I have a class that includes a DateTime property and a list of nested objects. When serializing, the DateTime is being output in UTC format, which is fine, but the nested objects are not being included in the JSON output unless they are explicitly marked. Here's a simplified version of my model: ```csharp public class Order { public int Id { get; set; } public DateTime OrderDate { get; set; } public List<Item> Items { get; set; } } public class Item { public int ItemId { get; set; } public string Name { get; set; } } ``` In my controller action, I create an order and return it: ```csharp [HttpGet] public ActionResult<Order> GetOrder(int id) { var order = new Order { Id = id, OrderDate = DateTime.UtcNow, Items = new List<Item> { new Item { ItemId = 1, Name = "Widget" }, new Item { ItemId = 2, Name = "Gadget" } } }; return order; } ``` When I test this endpoint, I receive the following JSON: ```json { "id": 1, "orderDate": "2023-10-01T12:00:00Z" } ``` The `Items` property is missing from the output. I've ensured that the `Items` list is initialized and contains data. This behavior is unexpected, as I thought that non-null collections would be serialized by default. I've also checked my `Startup.cs` and I haven't made any customizations to the `System.Text.Json` options that might affect serialization. I've tried adding the `[JsonPropertyName]` attribute to the `Items` property, but that didn't help. Is there something specific in ASP.NET Core 5 that I might be overlooking when it comes to JSON serialization? Any insights on how to resolve this would be greatly appreciated! What's the best practice here?