Java Type Generic as Argument for GSON

前端 未结 13 1702
陌清茗
陌清茗 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:36

    If programming in kotlin, we can use reified type parameter in inline function

    class GenericGson {
    
        companion object {
            inline fun <reified T : Any> Gson.fromJsonTokenType(jsonString: String): T {
                val type = object : TypeToken<T>() {}.type
                return this.fromJson(jsonString, type)
            }
    
            inline fun <reified T : Any> Gson.fromJsonType(jsonString: String): T = this.fromJson(jsonString, T::class.java)
    
            inline fun <reified T : Any> fromJsonTokenType(jsonString: String): T = Gson().fromJsonTokenType(jsonString)
    
            inline fun <reified T : Any> fromJsonType(jsonString: String): T = Gson().fromJsonType(jsonString)
        }
    }
    

    And use like below in your code

    val arrayList = GenericGson.fromJsonTokenType<ArrayList<Person>>(json)
    
    0 讨论(0)
提交回复
热议问题