Search code examples
c#json-deserializationsystem.text.json

How to deserialize an anonymous object using C# System.Text.Json and access its properties?


I have the following code:

var model = new
{
    Name = "Alexander"
};

var serializedModel = JsonSerializer.Serialize(model);
var deserializedModel = JsonSerializer.Deserialize<object>(serializedModel);
var name = deserializedModel!.GetType().GetProperty("Name");

The name variable is null as the "Name" property doesn't seem to exist. I do not have the model object when deserializing but just the JSON string.

I have tried using JsonConvert.DeserializeObject(serializedModel) from Newtonsoft and that seems to be working fine. However, I want to use System.Text.Json. Also, I have to use .GetType().GetProperty(...) as it's done like that in the external library I'm passing the deserialized object to.


Solution

  • After spending some time on the original issue I was able to get it running using Reflection.Emit and that might actually be the only way to achieve what I originally asked for as you have the properties from the JSON and you have to generate a class at runtime that has said properties.

    A more detailed answer can be found here: https://stackoverflow.com/a/29428640

    If you don't actually need something so complex then you can try to deserialize to ExpandoObject.