Java Type Generic as Argument for GSON

前端 未结 13 1785
陌清茗
陌清茗 2020-11-27 12:51

In GSON to get a list of objects you do

Gson gson = new Gson();
Type token = new TypeToken>(){}.getType();
return gson.fromJson(json         


        
13条回答
  •  眼角桃花
    2020-11-27 13:31

    In Kotlin you can simply use this function:

    inline fun  fromJson(json: String): T {
      return Gson().fromJson(json, object: TypeToken(){}.type)
    }
    

    and use it like

    val myTypes: List = fromJson(jsonString);
    

    It will parse any object including gereric types as List. Keyword inline and reified ensures that type will not be erased.

    For detail info I can recommend this Medium post

提交回复
热议问题