Deserialise a generic list in Gson

后端 未结 2 412
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 07:30

I want to write a generic function which deserialise a generic type List with Gson here is the code:

private  List GetListFromFile(String f         


        
2条回答
  •  不思量自难忘°
    2020-12-06 08:13

    There is no way to do it without passing actual type of T (as Class) to your method.

    But if you pass it explicitly, you can create a TypeToken for List as follows:

    private  List GetListFromFile(String filename, Class elementType) {
        ...
        TypeToken> token = new TypeToken>() {};
        List something = gson.fromJson(data, token.getType());
        ...
    }
    

    See also:

    • TypeToken

提交回复
热议问题