Kobek Kobek - 13 days ago 20
C# Question

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


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.


JSON.Net (i.e. Newtonsoft.Json) does this for you already. For example, lets start off with a basic class:

public class Thing
    public int SomeValue { get; set; }
    public string AnotherValue { get; set; }

And an instance of it:

var thing = new Thing { SomeValue = 5, AnotherValue = "blah" };

We can deserialise with a custom settings object, specifically setting the TypeNameHandling property

var settings = new JsonSerializerSettings
    TypeNameHandling = TypeNameHandling.All

var json = JsonConvert.SerializeObject(thing, settings);

Which will give output something like this:

    "$type":"Thing, Namespace",
    "SomeValue": 5,
    "AnotherValue": "blah"

And to get it back into the right kind of object, just use the same settings:

var anotherThing = JsonConvert.DeserializeObject(json, settings);