Parsing Json to List of Items with generic field with Gson

前端 未结 1 411
忘掉有多难
忘掉有多难 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 gc = new Query().getParsedCollection( ... );
    

    actually doesn't pass Game inside getParsedCollection(). here only tells the compiler that getParsedCollection() is supposed to return OwnCollection, 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  OwnCollection getParsedCollection(Class elementType) { ... }
    ...
    OwnCollection gc = new Query().getParsedCollection(Game.class);
    

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

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

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

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