Fuel: Generic GSon Deserializer

Created on 8 Jun 2017  路  4Comments  路  Source: kittinunf/fuel

Instead of coding a deserializer class on each Model Class, I prefer to have only one deserializer class.
See example below.

class Demo {

     companion object {
        @JvmStatic fun main(args: Array<String>) {
            "http://weathers.co/api.php?city=Madrid"
                    .httpGet()
                    .responseObject(Deserializer<Wheater>(Wheater::class.java)){ request, response, result ->
                        result.fold( { wheater ->
                            println(wheater.apiVersion)
                            println(wheater.data.location)
                        }
                        , { error ->
                            println("Error ${error.exception.message}")
                        })
                    }
        }
    }
}

/// generic deserializer
class Deserializer<T : Any> (val javaclassname: Class<T>) : ResponseDeserializable<T> {
    override fun deserialize(content: String) = Gson().fromJson(content, javaclassname)
}


data class Wheater (var apiVersion:String, var data:Datos)

data class Datos (var location:String)

Most helpful comment

Aha, that is one possibility to do that as well. But this is up to the client that uses library's api right? So, from Fuel's standpoint, there is no need to change anything?

PS.

You can make it even more simpler by using reified type from Kotlin

Something like this

inline fun <reified T: Any> typeToken() = object : TypeToken<T>() {}.type

inline fun <reified T: Any> Gson.fromJson(json: String): T = fromJson(json, typeToken<T>())

Then usage becomes something like this instead.

Gson().fromJson<Datos>()

All 4 comments

even simpler with:

.responseObject(Deserializer(Wheater::class.java)){ request, response, result ->

Aha, that is one possibility to do that as well. But this is up to the client that uses library's api right? So, from Fuel's standpoint, there is no need to change anything?

PS.

You can make it even more simpler by using reified type from Kotlin

Something like this

inline fun <reified T: Any> typeToken() = object : TypeToken<T>() {}.type

inline fun <reified T: Any> Gson.fromJson(json: String): T = fromJson(json, typeToken<T>())

Then usage becomes something like this instead.

Gson().fromJson<Datos>()

I think this is up to the client to supply the Deserializer class in whatever it suits you best, I believe we can close this issue.

 @SerializedName("screenshots") val screenshots: ArrayList<Link>

i have something like this in my data class,how to parse that using gson

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Querschlag picture Querschlag  路  5Comments

fnunezkanut picture fnunezkanut  路  6Comments

easazade picture easazade  路  6Comments

SleeplessByte picture SleeplessByte  路  3Comments

IvanKulikov picture IvanKulikov  路  5Comments