HugoMatilla
5/5/2016 - 11:40 AM

Kotlin Retrofit Custom JSON Deserializer, and Interceptor for Headers.kt

class AppRestService : IAppRestService {
    override fun getAppRestService(): IRestService {
        val httpClient = OkHttpClient().newBuilder()
        val interceptor = Interceptor { chain ->
            val request = chain?.request()?.newBuilder()?.addHeader("SomeHeader", "SomeHeaderProperty")?.build();
            chain?.proceed(request)
        }
        httpClient.networkInterceptors().add(interceptor)
        val customGson = GsonBuilder().registerTypeAdapter(MyClassCloud::class.java, MyClassCloudDeserializer("1")).create()
        val retrofit = Retrofit.Builder().baseUrl(IRestService.URL_BASE).addConverterFactory(GsonConverterFactory.create(customGson)).client(httpClient.build()).build()
        val scondoo = retrofit.create(IRestService::class.java)
        return scondoo
    }
}

class MyClassCloudDeserializer(val id: Int) : JsonDeserializer<MyClassCloud> {
    override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): MyClassCloud? {
        val root = json?.asJsonObject?.get("items")?.asJsonObject;
        val jsonStr = root?.get(id.toString())?.asJsonObject
        val article = Gson().fromJson(jsonStr, MyClassCloud::class.java)
        return article
    }
}

class MyClassRestService {

    @Throws(IOException::class)
    fun getMyClass(): MyClassCloud {
        val call = AppRestService().getAppRestService().getMyClass()
        val execution = call.execute()
        if (execution.isSuccessful) {
            return execution.body()
        } else {
            throw HttpException(execution.code(), execution.errorBody().string())
        }
    }
}

IRestService : {
  @GET("<URL_TO_GET_MY_CLASS>")
    fun getMyClass(): Call<MyClassCloud>
}
//{
//  "items": {
//    "452217": {
//      "id": 452217,
//      "title": "Title"
//      }
//    }
//  }