A
A
Alexander Kusak2018-09-30 13:50:20
C++ / C#
Alexander Kusak, 2018-09-30 13:50:20

How to instantiate an object from a function's type parameter?

There is a method in the Utils class

public static T getJsonList<T>(string json)
        {
            string newJson = "";
            T obj = new T();
            Debug.Log("getJsonList " + json);
            if(json.Substring(0, 1) != "{") {
                newJson = "{ \"array\": " + json + "}";
            } else {
                newJson = json;
            }
            T wrapper = JsonUtility.FromJson<T>(newJson);
            return wrapper;
        }

The line with the creation of an object of type T throws this error in the console:
Assets/Scripts/Utils.cs(20,21): error CS0304: Cannot create an instance of the variable type `T' because it does not have the new() constraint
itself this method is called from another class to which the object type is also passed as a parameter:
callback(Utils.JsonHelper.getJsonList<T>(www.downloadHandler.text));

Data is passed to this method like this:
RequestManager.apiGET<Models.GameModel>("gamble", param, resp => {
//...
})

Actually the question is how can you create an instance of the Models.GameModel object in the getJsonList method
or how to solve the problem that getJsonList does not want to parse the JSON string ( {"status": 0} ) into the model object giving an error

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
ColdSpirit, 2018-09-30
@ColdSpirit

https://docs.microsoft.com/ru-ru/dotnet/csharp/lan...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question