i want to make a dynmamic class in C# out of a Json.
I Know i can you deserialize to convert the json but my problem is:
If i know how the json looks like (e.g. { "id": "5", "name": "Example" }
i can call the value with obj.id or obj.name
BUT
i have a JSON with one property Array that could be diffrent in every instance. E.G.
{
"id": "5",
"name": "Example",
},
"config": {
"Time": "13:23",
"Days": ["Monday", "Thuesday"]
}
or
{
"id": "5",
"name": "Example",
},
"config": {
"ServerURL": "https://example.com",
"Category": "API"
}
So how i can convert this diffrent JSONs to ONE dynamic object?
dynamic o = new ExpandoObject();
o.Time = "11:33";
var n = Newtonsoft.Json.JsonConvert.SerializeObject(o);
dynamic oa = Newtonsoft.Json.JsonConvert.DeserializeObject<ExpandoObject>(n);
Console.Write(oa.Time);
Console.Read();
You could do something like:
var jObj = JObject.Parse(jsonData);
And jObj becomes your 'ONE dynamic object', to access further properties:
var idObject= jObj["id"].ToObject<string>();
Or for config, you could do:
var configInfo = jObj["config"].ToObject<Dictionary<string, string>>();
PS: I had similar quesiton, you can check the question at JSON to object C# (mapping complex API response to C# object) and answer https://stackoverflow.com/a/46118086/4794396
EDIT:
You may want to map config to map your config info with something like .ToObject<Dictionary<string, object>>()
since it could be anything..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With