tl:dr JsonNode is the recommended way but dynamic typing with deserializing to ExpandoObject works and I am not sure why.

It is not possible to deserialize to dynamic in the way you want to. JsonSerializer.Deserialize<T>() casts the result of parsing to T. Casting something to dynamic is similar to casting to object

Type dynamic behaves like type object in most circumstances. In particular, any non-null expression can be converted to the dynamic type. The dynamic type differs from object in that operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time

docs.

The following code snippet shows this happening with your example.

var jsonString = "{\"foo\": \"bar\"}";
dynamic data = JsonSerializer.Deserialize<dynamic>(jsonString);
Console.WriteLine(data.GetType());

Outputs: System.Text.Json.JsonElement

The recommended approach is to use the new JsonNode which has easy methods for getting values. It works like this:

JsonNode data2 = JsonSerializer.Deserialize<JsonNode>(jsonString);
Console.WriteLine(data2["foo"].GetValue<string>());

And finally trying out this worked for me and gives you want you want but I am struggling to find documentation on why it works because according to this issue it should not be supported but this works for me. My System.Text.Json package is version 4.7.2

dynamic data = JsonSerializer.Deserialize<ExpandoObject>(jsonString);
Console.WriteLine(data.GetType());
Console.WriteLine(data.foo);
Answer from JGilmore on Stack Overflow
Top answer
1 of 3
55

tl:dr JsonNode is the recommended way but dynamic typing with deserializing to ExpandoObject works and I am not sure why.

It is not possible to deserialize to dynamic in the way you want to. JsonSerializer.Deserialize<T>() casts the result of parsing to T. Casting something to dynamic is similar to casting to object

Type dynamic behaves like type object in most circumstances. In particular, any non-null expression can be converted to the dynamic type. The dynamic type differs from object in that operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time

docs.

The following code snippet shows this happening with your example.

var jsonString = "{\"foo\": \"bar\"}";
dynamic data = JsonSerializer.Deserialize<dynamic>(jsonString);
Console.WriteLine(data.GetType());

Outputs: System.Text.Json.JsonElement

The recommended approach is to use the new JsonNode which has easy methods for getting values. It works like this:

JsonNode data2 = JsonSerializer.Deserialize<JsonNode>(jsonString);
Console.WriteLine(data2["foo"].GetValue<string>());

And finally trying out this worked for me and gives you want you want but I am struggling to find documentation on why it works because according to this issue it should not be supported but this works for me. My System.Text.Json package is version 4.7.2

dynamic data = JsonSerializer.Deserialize<ExpandoObject>(jsonString);
Console.WriteLine(data.GetType());
Console.WriteLine(data.foo);
2 of 3
3

I have tried using System.Text.Json in a dynamic way and it just does not work in an easy and meaningful way it seems. So while not a direct answer to your question, but I was "forced" to use the good old Newtonsoft.Json that just works:

dynamic result = JObject.Parse(message);
🌐
Reddit
reddit.com › r/dotnet › best way to deserialize a dynamic json?
r/dotnet on Reddit: Best way to deserialize a dynamic JSON?
August 15, 2024 -

[SOLVED - Just use a Dictionary<string, string>]

Hey, guys. I'm working on an dotNet 8 app and I'm in a position that I have this problematic object structure:

class MyStrangeClass {
  ...
  string Details { get; set; }
  ...
}

And this Details property will contain a JSON that has this structure:

{
  "main_details": "{ \"Some Key\": \"Some Value\", ..... }",
  "extra_details": "{ \"Some Key\": \"Some Value\", ...... }"
}

The main_details and extra_details are contants, but their values are another JSONs with keys that are not. There can be any number of any keys but the value will always be a string.

This works right now as the application just send this to the front-end that has no problem working with it in JS. But now, I have to develop a feature that creates a CSV file with all those keys and values from the JSONs inside main_details and extra_details, so I must deserialize them inside the dotNet app. I have no clue how to deserialize this complex dynamic object so it can be consumed in a CSV generation library. I have googled it but answers vary a lot.
Right now the only thing I'm certain is that I will have 2 steps of deserialization.

Discussions

How useful is C# "dynamic" with System.Text.Json.Nodes.JsonObject?
Currently JsonObject supports C# "dynamic" which primarily means an instance of JsonObject can get\set a property value without having to use a string for the property name. Although dyna... More on github.com
🌐 github.com
33
May 24, 2021
how to deserialize json into dynamic object in c# and update field
Hello , I have a Json file that dynamically changes as the pages of the Json keep change their names so in order to Deserialize it I used this code var dynamicObject= await XMLManager.DeserializeJson(pathT) and here is a sample of my… More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
April 3, 2023
system.text.json with dynamic object names
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Download Microsoft Edge More info about Internet Explorer and Microsoft Edge ... I have a problem with dynamic object names. Can anyone please help me with deserializing this json into c# ... More on learn.microsoft.com
🌐 learn.microsoft.com
2
0
c# - How do you read a simple value out of some json using System.Text.Json? - Stack Overflow
Also, because of nontrivial behaviour ... serialize/deserialize JSON strings. I understand that System.Text.Json is supposed to be faster than Newtonsoft.JSON, but I believe this has a lot to do with ser/deser from/to specific POCO classes. Anyway, speed was not on our list of pros/cons for this decision, so YMMV. Long story short, for the time being I wrote a small dynamic object wrapper ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Code Maze
code-maze.com › home › how to deserialize json into dynamic object in c#
How to Deserialize JSON Into Dynamic Object in C# - Code Maze
April 4, 2024 - In the legacy ASP.NET MVC application, we would get a Dictionary<string, object> when using dynamic with the native deserializer class: JavaScriptSerializer. That was not a true dynamic thing of course, but surely offered a bit of flexibility in managing. However, the flexibility of dynamic comes at the price of performance. That’s why the .NET team set dynamic aside the design considerations of System.Text.Json as they want this to come out as a high-performant library.
🌐
TheCodeBuzz
thecodebuzz.com › home › system.text.json deserialize json into c# object/type dynamically
System.Text.Json Deserialize JSON into C# Object Dynamically | TheCodeBuzz
January 21, 2024 - System.Text.Json Deserialize JSON into C# Object Dynamically with and without class. Use generics simple steps to convert your JSON using System.Text.JSON.
🌐
GitHub
github.com › dotnet › runtime › issues › 53195
How useful is C# "dynamic" with System.Text.Json.Nodes.JsonObject? · Issue #53195 · dotnet/runtime
May 24, 2021 - Reload to refresh your session. ... area-System.Text.Jsondesign-discussionOngoing discussion about design without consensusOngoing discussion about design without consensus ... Currently JsonObject supports C# "dynamic" which primarily means an instance of JsonObject can get\set a property value without having to use a string for the property name.
Published   May 24, 2021
Author   steveharter
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › standard › serialization › system-text-json › deserialization
How to deserialize JSON in C# - .NET | Microsoft Learn
A common way to deserialize JSON is to have (or create) a .NET class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer.Deserialize method.
Find elsewhere
Top answer
1 of 2
1

Check one of approaches:

public class Data
{
    public string @class { get; set; }
    public Value value { get; set; }
}

public class Value
{
    public string[] groupNames { get; set; }
    public string itemType { get; set; }
    public string[] tags { get; set; }
    public string label { get; set; }
    public string category { get; set; }
}

. . .

Dictionary dictionary = JsonSerializer.Deserialize>( json );

where json is your string. See also other parameters of Deserialize.

Sample usage:

string category = dictionary["TreppenhausOG"].value.category;

If required, use "Manage NuGet Packages" window to add a reference to System.Text.Json.

2 of 2
0

@Bernd Schmal , Viorel-1's solution is good, I also make a code example for it, you could refer to the following code:

using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Text.Json;  
  
namespace ConsoleApp1  
{  
    internal class Program  
    {  
        static void Main(string[] args)  
        {  
            string jsonstr = File.ReadAllText("D:\\1.json");  
            Root myDeserializedClass = JsonSerializer.Deserialize(jsonstr);  
  
            Console.WriteLine(myDeserializedClass.WohnzimmerEG.value.category);  
        }  
    }  
  
    public class Value  
    {  
        public List groupNames { get; set; }  
        public string itemType { get; set; }  
        public List tags { get; set; }  
        public string label { get; set; }  
        public string category { get; set; }  
    }  
  
    public class WohnzimmerEG  
    {  
        public string @class { get; set; }  
        public Value value { get; set; }  
    }  
  
    public class TreppenhausOG  
    {  
        public string @class { get; set; }  
        public Value value { get; set; }  
    }  
  
    public class Kinozimmer  
    {  
        public string @class { get; set; }  
        public Value value { get; set; }  
    }  
  
    public class Root  
    {  
        public WohnzimmerEG WohnzimmerEG { get; set; }  
        public TreppenhausOG TreppenhausOG { get; set; }  
        public Kinozimmer Kinozimmer { get; set; }  
    }  
}  
   

You could get the WohnzimmerEG's category like the following:

Console.WriteLine(myDeserializedClass.WohnzimmerEG.value.category);

Result:


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

🌐
Codemia
codemia.io › knowledge-hub › path › deserialize_json_into_c_dynamic_object
Deserialize JSON into C# dynamic object?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
CodeGenes
codegenes.net › blog › is-it-possible-to-deserialize-json-string-into-dynamic-object-using-system-text-json
Is It Possible to Deserialize JSON String into Dynamic Object Using System.Text.Json? — codegenes.net
JsonSerializer.Deserialize<dynamic>(json) returns a JsonElement (a struct representing a JSON value), not a dynamic object with dot-notation access. To work with dynamic-like flexibility, we need workarounds.
🌐
Kunal Shah
iamkunalshah.com › deserialize-json-to-dynamic-object-csharp
Deserialize JSON into C# dynamic object with ExpandoObject - Kunal Shah
May 16, 2023 - In this example, we use the JsonSerializer class from the System.Text.Json namespace to deserialize the JSON string into an ExpandoObject. The Deserialize method takes two arguments – the JSON string and the type to deserialize to. In this case, we specify ExpandoObject as the type.
🌐
Reddit
reddit.com › r/dotnet › writing list to json file via system.text.json
r/dotnet on Reddit: Writing list<dynamic> to json file via system.text.json
August 8, 2023 -

I have a very complex object that is currently in a List<dynamic> object and would like to write this out to json file. I managed to do this with newtonsoft but it has skipped some data and is not in the format i wanted. Someone at work nudged me to use system.text.json however i now noticed an error with invalid arguments which most likely are causing blank output in the nested data lots of empty arrays returned.

All the guides i see use newtonsoft or poco classes and give the dynamic a type. Is there anything I should be looking into to get this working hopefully an option i can pass into the serializer

Top answer
1 of 2
1
Just use VS feature called “Paste JSON as class” and serialize/deserialize your json to that generated POCO https://learn.microsoft.com/en-us/visualstudio/ide/reference/paste-json-xml?view=vs-2022
2 of 2
1
What's the underlying type? Dynamic is not a type, it just hides it, in simple terms it's like syntax sugar for setter and getter methods. Could you share examples of the issues you are facing? When I had to read and write arbitrary JSON as dynamic, I added three types extending DynamicObject: DynamicDictionary as a stand-in for objects, DynamicArray and DynamicAnonymous. Then I added three JsonConverters: for DynamicDictionary, DynamicArray and dynamic. The last one is basically just a proxy to have Read() create the other two types, just make sure to handle empty typeof(object) to prevent infinite loops. Short description. There are a bunch of edge cases I had to find and handle, like when to use object and when to use dynamic, or when to implement IDictionary and when not to, compiler generated non-public types, when to lie about property existence and so on. I'd not recommend doing it if you don't really have to. If there is any way you can put the data into a structured form, you'd probably have a much better time. Maybe you can add union/sum type like classes as an erased wrapper for a limited, explicitly defined number of types? Ex: public record Foo(string Name); public record Bar(int Id); public enum ContentType { Foo, Bar } public record Content(ContentType ContentType) { public Foo? FooValue { get; init; } public Bar? BarValue { get; init; } } And then you add a JsonConverter and call JsonSerializer.Serialize for the respective value instead of writing an extra object for Content itself. You'd be able to write JSON like this: [{"Name":"foo"},{"Id":1}] You can of course build similar converters around more generalized structures like a dictionary wrapper or whatever. Which still begs the question what your actual types are and how you're constructing the data...
🌐
Makolyte
makolyte.com › csharp-deserialize-json-to-dynamic-object
C# - Deserialize JSON to dynamic object | makolyte
January 26, 2025 - If you want to deserialize JSON without having to create a bunch of classes, you can either deserialize to a dictionary or deserialize to a dynamic object with Newtonsoft.Json. Here’s an example. Let’…
🌐
Acv
acv.engineering › posts › dynamic-json-serialization
Dynamic JSON Serialization in System.Text.Json – ACV Tech Blog
September 24, 2021 - However, since that happens once at startup, it’s not possible to have it be dynamic and the JsonSerializerOptions handles metadata and caching for the different types you serialize. This provides additional performance improvements, but limits our options for a situation like we have today.
🌐
Quora
quora.com › C-How-do-you-deserialize-JSON-into-a-dynamic-object
C#: How do you deserialize JSON into a dynamic object? - Quora
Answer (1 of 4): Deserialize JSON using Newtonsoft.Json. To get it, use NuGet Package Manager in Visual Studio. The steps on how to get the package are documented here by Microsoft (Literally the example is Newtonsoft.Json): Install and use a NuGet package in Visual Studio I’ll post the screensh...
🌐
Medium
medium.com › @zhenkai.dev › handling-dynamic-json-structures-with-custom-converters-in-c-831fb6bb98e4
Handling Dynamic JSON Structures with Custom Converters in C# | by zhenkai.dev | Medium
October 25, 2024 - Just create a POCO class that represent the data structure of your JSON object, and use it in JsonSerializer.Deserialize<T>() , then you have your JSON deserialized! However, in my JSON example, this is not as simple as what the MS Doc demonstrated.
🌐
CodeProject
codeproject.com › Articles › 5284591 › Adding-type-to-System-Text-Json-Serialization-like
Adding $type to System.Text.Json Serialization like in Newtonsoft for Dynamic Object Properties - CodeProject
November 6, 2020 - This article describes a technique to serialize models containing dynamic types with System.Text.Json JsonSerializer, that doesn’t support $type.
🌐
GitHub
github.com › dotnet › runtime › issues › 31175
System.Text.Json support for DynamicObject. · Issue #31175 · dotnet/runtime
October 16, 2019 - ExpiresUtc { get; set; } public string Notes { get; set; } } [Fact] public void CanSerializeSimpleModel() { var token = new NewToken { OrganizationId = "TEST_ORG_ID", ProjectId = "TEST_PROJECT_ID" }; string json = System.Text.Json.JsonSerializer.Serialize(token); _logger.LogInformation(json); var delta = System.Text.Json.JsonSerializer.Deserialize<Delta<NewToken>>(json, settings); Assert.Equal(2, delta.GetChangedPropertyNames().Count()); }
Author   niemyjski