Orilious
Orilious

Reputation: 329

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?

Upvotes: 1

Views: 63

Answers (1)

derHugo
derHugo

Reputation: 90630

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];

Upvotes: 2

Related Questions