CodexBloom - Programming Q&A Platform

C# - Querying Nested JSON Objects Using System.Text.Json Leads to Missing Properties

👀 Views: 453 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
c# json serialization dotnet C#

I've been banging my head against this for hours. I'm upgrading from an older version and I've encountered a strange issue with I've looked through the documentation and I'm still confused about I'm trying to deserialize a nested JSON object into a C# class using `System.Text.Json`, but I'm working with issues where certain properties are not being populated. The JSON structure looks something like this: ```json { "name": "John Doe", "address": { "street": "123 Main St", "city": "Anytown", "zip": "12345" }, "phones": [ { "type": "home", "number": "555-1234" }, { "type": "work", "number": "555-5678" } ] } ``` I have the following C# classes to match this structure: ```csharp public class Person { public string Name { get; set; } public Address Address { get; set; } public List<Phone> Phones { get; set; } } public class Address { public string Street { get; set; } public string City { get; set; } public string Zip { get; set; } } public class Phone { public string Type { get; set; } public string Number { get; set; } } ``` When I attempt to deserialize the JSON using the following code: ```csharp string jsonString = // your JSON string here; var person = JsonSerializer.Deserialize<Person>(jsonString); ``` I find that the `Address` property is always null, and the `Phones` list is empty. I suspect it might have something to do with casing or property names not matching, but I have checked and they seem to align correctly. I'm using .NET 5.0, and the relevant `JsonSerializerOptions` for casing is set like this: ```csharp var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; ``` Even with this setting, the deserialization doesn't work as expected. I've also tried removing the `PropertyNamingPolicy` to see if it made any difference, but that hasn't resolved the scenario either. Has anyone else encountered this question, or does anyone have insights into what might be going wrong? Am I missing something obvious? This is for a REST API running on Windows 11. Hoping someone can shed some light on this. Is there a simpler solution I'm overlooking? I'm coming from a different tech stack and learning C#. Thanks in advance!