How do I deserialize a JSON to an anonymous type?
I have this working code that's:
- defining a JSON with Foo and Bar fields
- defining a model as anonymous type with Foo property
- deserializing the JSON using the generic method
[Fact]
public void Test1()
{
const string json = """
{
"Foo": "a",
"Bar": "b"
}
""";
var model = new
{
Foo = default(string),
};
var deserialized = Deserialize(json, model);
var a = deserialized.Foo;
a.Should().Be("a");
}
private T Deserialize<T>(string json, T model) => JsonSerializer.Deserialize<T>(json) ?? model;
I would like to do the same without the generic Deserialize method. Below the code:
[Fact]
public void Test2()
{
const string json = """
{
"Foo": "a",
"Bar": "b"
}
""";
var model = new
{
Foo = default(string),
};
var deserialized = JsonSerializer.Deserialize<??????>(json);
string a = deserialized.Foo;
a.Should().Be("a");
}
Not sure what to put instead of the ??????
. Ideally I'd like to specify something like typeof(model)
or model.GetType()
, but those are not accepted by the compiler
CodePudding user response:
Not sure that this will suit your actual use case, but for current one you can try using Dictionary
:
var deserialized = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
string a = deserialized["Foo"];
Or just introduce the class, with record
s (C# 9) and file
keyword (C# 11) it should extremely simple and effortless:
file record RecordForTest1(string Foo, string Bar);
[Fact]
public void Test1()
{
// ...
var deserialized = JsonSerializer.Deserialize<RecordForTest1>(json);
}
CodePudding user response:
You can use ExpandoObject
.
var deserialized = JsonSerializer.Deserialize<ExpandoObject>(json);
string a = deserialized.Foo.ToString();
...
If you want you can also create extension method like below:
public static dynamic? DeserializeAsDynamic(this string json)
{
var result = JsonConvert.DeserializeObject<ExpandoObject>(json);
return result;
}
Sample usage:
dynamic obj = json.DeserializeAsDynamic();