5

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?

1
  • EDIT: only the field "config" have different properties, the rest are always the same Commented Jun 6, 2019 at 6:31

4 Answers 4

6
        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();
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

0
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

3 Comments

True but if i have 100 different Jsons with different Configs so i have to make 100 classes, right?
ExpandoObject In System.Dynamic namespace look at usage
look i just posted answer
-2

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

1 Comment

As mentioned by OP, there isn’t a fixed T yet since the structure is changing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.