[C#] Pass a method an unknown type, create a proper instance, then overwrite vars with JsonUtility

I want to pass a function that builds objects from a string that represents the type and a JSON string.
How do I do this dynamically? I’d rather not create a massive switch case to identify the type string.

void BuildUnknownObjectFromJSON(string objclassname, string jsonstring){
    Type type = Type.getType(objclassname);

    // this?
    GameObject obj = new GameObject() as type;
    obj = JsonUtility.FromJson<type>(jsonstring);

    // Or this?
     var obj = JsonUtility.FromJsonOverwrite(jsonstring) as type;

    // Or this?
    object obj = Activator.CreateInstance(type);
    JsonUtility.FromJsonOverwrite(jsonstring, obj)
}

Hi there,
could this be achieved by making the method generic?

private T BuildUnknownObjectFromJSON<T>(string jsonstring){
   //Include error checking
    var obj = JsonUtility.FromJson<T>(jsonstring);
    return obj;
}

.....

TestObject obj = BuildUnknownObjectFromJSON<TestObject>(myJson);

[EDIT] beware that the above code hasn’t been tested

Learning resource: Generics - Unity Learn

Hope it helps!
Joe

1 Like