Parsing Json to List of Items with generic field with Gson

前端 未结 1 390
忘掉有多难
忘掉有多难 2021-01-16 01:22
public class OwnCollection{
    private int size;
    private List> data;
}

public class ResponseItem{
    private Str         


        
相关标签:
1条回答
  • 2021-01-16 02:13

    It doesn't work this way, because the following code

    OwnCollection<Game> gc = new Query().<Game>getParsedCollection( ... );
    

    actually doesn't pass Game inside getParsedCollection(). <Game> here only tells the compiler that getParsedCollection() is supposed to return OwnCollection<Game>, but T inside getParsedCollection() (and parseToGenericCollection()) remains erased, therefore TypeToken cannot help you to capture its value.

    You need to pass Game.class as a parameter instead

    public <T> OwnCollection<T> getParsedCollection(Class<T> elementType) { ... }
    ...
    OwnCollection<Game> gc = new Query().getParsedCollection(Game.class);
    

    and then use TypeToken to link OwnCollection's T with elementType as follows:

    Type type = new TypeToken<OwnCollection<T>>() {}
        .where(new TypeParameter<T>() {}, elementType)
        .getType();
    

    Note that this code uses TypeToken from Guava, because TypeToken from Gson doesn't support this functionality.

    0 讨论(0)
提交回复
热议问题