简体   繁体   中英

How to decide for type of a property when creating an instance?

I'm coding an online game in Unity. I'm also using a custom response shape for my HTTP responses, like below:

public class Response
{
    public string status;
    public List<string> messages;
    public List<T> data;
}

I want to decide on the type of "data" property when I receive an HTTP response. It can be any custom type. for example from type player:

public class Player
{
    public string id;
    public string name;
    public int gems;

    public Player(string id, string name, int gems)
    {
        this.id = id;
        this.name = name;
        this.gems = gems;
    }
}

so the shape of response, in this case, will be like below:

public class Response
{
    public string status;
    public List<string> messages;
    public List<Player> data;
}

so I can parse and assign it like:

var player = JsonUtility.FromJson<Response>(response.ReadAsString()).data[0];

or for other use cases like:

var players = JsonUtility.FromJson<Response>(response.ReadAsString()).data;

but it will be different for each response around the code and I don't want to create so many classes for each.

Is this even possible? What are the options or/and the best way? How can I implement it?

Not sure if Unity likes that but you could try and make the Response class generic

[Serializable]
public class Response<T>
{
    public string status;
    public List<string> messages;
    public List<T> data;
}

and then use

var players = JsonUtility.FromJson<Response<Player>>(response.ReadAsString()).data;
var player1 = players[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM