CodexBloom - Programming Q&A Platform

how to to deserialize JSON with dynamic properties in C# 10 using System.Text.Json

👀 Views: 92 💬 Answers: 1 📅 Created: 2025-06-13
c# json serialization dotnet systemtextjson C#

I'm testing a new approach and I'm relatively new to this, so bear with me... I'm prototyping a solution and I'm building a feature where I'm sure I'm missing something obvious here, but I'm having trouble deserializing JSON that has dynamic properties into a strongly-typed C# object using System.Text.Json in .NET 6... The JSON structure I'm dealing with can look like this: ```json { "name": "John Doe", "age": 30, "additionalInfo": { "hobbies": ["reading", "gaming"], "employed": true } } ``` I created a class to represent the data like this: ```csharp public class Person { public string Name { get; set; } public int Age { get; set; } public Dictionary<string, object> AdditionalInfo { get; set; } } ``` When I try to deserialize the JSON using the following code: ```csharp var jsonString = "{ \"name\": \"John Doe\", \"age\": 30, \"additionalInfo\": { \"hobbies\": [\"reading\", \"gaming\"], \"employed\": true } }"; var person = JsonSerializer.Deserialize<Person>(jsonString); ``` I get the following behavior message: ``` System.Text.Json.JsonException: The JSON value could not be converted to System.Object. ``` I’ve tried various approaches, including changing the type of `AdditionalInfo` to `JsonElement`, but that has not resolved the scenario. I’ve also ensured that the JSON string is valid using online validators. Could someone point me in the right direction on how to properly deserialize this JSON structure with dynamic properties into my C# class? Is there a better way to handle dynamic or unknown properties in the JSON? Has anyone else encountered this? Any feedback is welcome! I'm coming from a different tech stack and learning C#. Any feedback is welcome! I'm using C# stable in this project. I'm open to any suggestions. Thanks for your help in advance!