jeudi 2 juin 2016

C# Reflection, create instance from text

I want to create different types based on some text. I have tried the following without success:

JSON input:

[{"Type":"Book","Details":{"Name":"Book1","Chapter":"1","StartPage":"5","EndPage":"23"}},{"Type":"WebPage","Details":{"Name":"Page1","Url":"sometesturl.com","PageTypeIDs":"1"}}]

Since I do not want to change code every time a new type is added I tought reflection might be the solution.

List<Source> sources = new List<Source>();

dynamic[] items = jsSerializer.Deserialize<dynamic>(validjson);
foreach (var item in items)
        {
            string type = item["Type"];

            string serialized = jsSerializer.Serialize(item["Details"]);

            Type t = Type.GetType(type);
            var instance = createInstanceFromJSON(t, serialized);

            sources.Add(instance);
        }

Will give the following error: 'Cannot be converted from 'System.Type' to 'ProjectManager.Sources'' note that the type is in a seperate DLL called ProjectManager.

Here's the method:

private T createInstanceFromJSON<T>(T type, string json) where T : class
    {
        ConstructorInfo construtorInfo = typeof(T).GetConstructor(new[] { typeof(string) });
        ParameterInfo contructor = construtorInfo.GetParameters()[0];
        object defaultValue = contructor.DefaultValue;

        var item = (T)Activator.CreateInstance(typeof(T), defaultValue);

        item = jsSerializer.Deserialize<T>(json);

        return item;

    }





Aucun commentaire:

Enregistrer un commentaire