Custom converter for Retrofit 2

Solution 1:

I was looking for a simple example about how to implement a custom converter for Retrofit 2. Unfortunately found none.

I found this example but, at least for me, it's too complicated for my purpose.

Happilly, I found a solution.

This solution is to use GSON deserializers.

We don't need to create a custom converter, we just have to customize the GSON converter.

Here is a great tutorial. And here is the code I used to parse the JSON described in my question:

  • Login Deserializer: Defines how to parse the JSON as an object of our target class (using conditionals and whatever we need).

  • Custom GSON converter: Builds a GSON converter that uses our custom deserializer.

Solution 2:

I found @JCarlos solution to be precise, quick and correct. I needed to implement custom Date converter for Retrofit 2 on Android. It seems that you need to register a new type serializer in GSonConverterFactory. Implementation is done in Kotlin lang.

class RetrofitDateSerializer : JsonSerializer<Date> {
    override fun serialize(srcDate: Date?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement? {
        if (srcDate == null)
            return null
        val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
        val formatted = dateFormat.format(srcDate)
        return JsonPrimitive(formatted)
    }
}

and the registration:

private fun buildGsonConverterFactory(): GsonConverterFactory {
    val gsonBuilder = GsonBuilder()
    // Custom DATE Converter for Retrofit
    gsonBuilder.registerTypeAdapter(Date::class.java, RetrofitDateSerializer())
    return GsonConverterFactory.create(gsonBuilder.create())
}

@Provides @Singleton
internal fun providesRetrofit(applicationContext: Context): Retrofit {
    return Retrofit.Builder()
            .baseUrl(GluApp.Static.BASE_REST_URL_ADDR)
            .addConverterFactory(
                    buildGsonConverterFactory())
            .build()
}