Get nested JSON object with GSON using retrofit

前端 未结 13 1030
挽巷
挽巷 2020-11-22 17:04

I\'m consuming an API from my android app, and all the JSON responses are like this:

{
    \'status\': \'OK\',
    \'reason\': \'Everything was fine\',
    \         


        
13条回答
  •  野性不改
    2020-11-22 17:22

    Here's a Kotlin version based on the answers by Brian Roach and AYarulin.

    class RestDeserializer(targetClass: Class, key: String?) : JsonDeserializer {
        val targetClass = targetClass
        val key = key
    
        override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): T {
            val data = json!!.asJsonObject.get(key ?: "")
    
            return Gson().fromJson(data, targetClass)
        }
    }
    

提交回复
热议问题