jeudi 13 avril 2017

C# Dynamic Type Initialization From JSON

I am trying to dynamically instantiate a class from my visual studio solution based on a JSON string.

Before I describe my exact issue I want to give an example of what I want to achieve. Say I have the following JSON :

{
    "Type": "AutoIncrementTag,
    "StartFrom": 0,
    "Skip": 10,
    "LeadingZero": false
}

So from that Json, I want to find the class called "AutoIncrementTag" and instantiate it, setting its "StartFrom", "Skip" and "LeadingZero" parameters to the correspoding values.

Note 1: I have a couple of theese "Tag" classes and I want to instantiate a different on the "Type" attribute in my Json string.

Note 2: My Json string will contain more than 1 of these class "descriptions" (I believe they are called JSON Objects but I'm not too familliar with the JSON format just yet)

Note 3: I am using Newtonsoft.Json for all the Json parsing/converting.

So, now for my issue.

I managed to get the Type property using

JObject.Parse(myJsonString).GetValue("Type").ToString();

However, how would I go about getting all the other values, since they will be different depending on what Type I have? (I need a way to dynamically iterate and get the values of the other properties.)

And second, how do I then map these properties to a C# object. I thought about using

Activator.CreateInstance(Type type, object[] args)

But how can I (dynamically) get an object[] from the properties described in my json format.





Aucun commentaire:

Enregistrer un commentaire