Johannes Zeiße
Johannes Zeiße

Reputation: 63

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?

Upvotes: 5

Views: 10949

Answers (4)

AD8
AD8

Reputation: 2208

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

Upvotes: 5

Ausl&#228;nder
Ausl&#228;nder

Reputation: 499

        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();

Upvotes: 6

Ausl&#228;nder
Ausl&#228;nder

Reputation: 499

public class YourObject
{
   public string id;
   public string Example;
   public YourConfig config;
}
public class YourConfig
{
   public string Time;
   public string[] Days;
   public string ServerUrl;
   public string Category;
}

Json will convert your object based on property(Field name ) if your json contains example ServerURl and Category Time days will be null and vice versa.You can check based on null which json arrived

Upvotes: 0

jitendra
jitendra

Reputation: 1

you can use this approach, this has worked perfectly for me.

    var vModel = JsonConvert.DeserializeObject<T>(JsonData, new IsDateTimeConverter { DateTimeFormat = "dd/mm/yyyy", culture = cultureInfo.InvariantCulture});

Upvotes: -2

Related Questions