Skip to content

Instantly share code, notes, and snippets.

@Miha-x64
Created March 31, 2017 18:44
Show Gist options
  • Save Miha-x64/5b0dbfaf976109d196c071133b40d5ba to your computer and use it in GitHub Desktop.
Save Miha-x64/5b0dbfaf976109d196c071133b40d5ba to your computer and use it in GitHub Desktop.
Such deseriazers will help you in processing responses from back-ends which return 200 HTTP code all the time.
object class BadBackendResponseDeserializer : JsonDeserializer<Any?> {
// register all adapters you need
private val gson = GsonBuilder()
.registerTypeAdapter(Post::class.java, WallPostAdapter)
.registerTypeAdapter(Attachment::class.java, AttachmentAdapter)
.registerTypeAdapter(User::class.java, UserAdapter)
.registerTypeAdapter(Group::class.java, GroupAdapter)
.create()
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Any? {
val obj = json.asJsonObject
val resp = obj.get("response")
val err = obj.getAsJsonObject("error")
if (err == null && resp != null) { // got response, no error, just deserialize
return gson.fromJson(resp, typeOfT)
}
// handle error otherwise
val code = err.get("error_code")?.asInt
val msg = err.get("error_msg")?.asString
throw when (code) {
5 -> AuthException("Vk error code: 5. Message: $msg")
else -> GenericException("Vk error code: $code. Message: $msg")
}
}
}
fun usageExample() {
val deserializer = BadBackendResponseDeserializer
val gson = GsonBuilder() // regster this deserializer for all types you use as Retrofit Call<type parameter>
.registerTypeAdapter(TypeTokens.Posts, deserializer)
.registerTypeAdapter(TypeTokens.Users, deserializer)
.registerTypeAdapter(TypeTokens.Groups, deserializer)
.registerTypeAdapter(Void::class.java, deserializer)
.create()
val retrofit = Retrofit.Builder()
.baseUrl("https://api.vk.com/method/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build() // create a converter factory ^ with your Gson instance
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment