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);
JsonNode
in .Net 6 - github.com/dotnet/runtime/issues/31175#issuecomment-937646022 – GoyetteObjectAsPrimitiveConverter
from this answer to C# - Deserializing nested json to nested Dictionary<string, object> has an option to deserialize JSON objects to .NET ExpandoObjects. Demo here: dotnetfiddle.net/1Y6hI6. Is that what you want? – ChestertonJSON
with dynamic usingSystem.Text.Json
: https://mcmap.net/q/471335/-taking-a-json-array-with-file-paths-to-update-the-json-array-for-date-last-modified – HeywardJsonDocument.Parse
which is a good way of doing it IMO - but I’m not seeing an actualdynamic
object? – Alkyd