Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dynamic Object in C# out of json

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?

like image 592
Johannes Zeiße Avatar asked Jun 06 '19 06:06

Johannes Zeiße


2 Answers

        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();
like image 109
phantasm Avatar answered Sep 19 '22 16:09

phantasm


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..

like image 40
AD8 Avatar answered Sep 17 '22 16:09

AD8