Skip to content

Instantly share code, notes, and snippets.

@iambaljeet
Created January 4, 2022 12:07
Show Gist options
  • Save iambaljeet/450365c5b998410ef1be1e4de358ee4a to your computer and use it in GitHub Desktop.
Save iambaljeet/450365c5b998410ef1be1e4de358ee4a to your computer and use it in GitHub Desktop.
Custom Adapter for setting default value for enums insude API response.
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.annotations.SerializedName
import java.lang.reflect.Type
class EnumJsonAdapter<T : Enum<T>>(private val defaultValue: Enum<T>) : JsonDeserializer<Enum<T>> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?,
): Enum<T> {
return try {
if (typeOfT is Class<*> && typeOfT.isEnum) {
val clazz = typeOfT as? Class<Enum<T>?>
val value = getValue(clazz, json?.asString)
val valueOf = java.lang.Enum.valueOf(typeOfT as? Class<Enum<T>?>, value)
return valueOf
?: defaultValue
} else {
defaultValue
}
} catch (e: Exception) {
e.printStackTrace()
return defaultValue
}
}
fun getValue(clazz: Class<*>?, json: String?): String? {
val declaredFields = clazz?.declaredFields
declaredFields?.forEach {
val annotation = it.getAnnotation(SerializedName::class.java)
if (annotation?.value != null && annotation.value == json) {
return it.name
}
}
return json
}
}
@iambaljeet
Copy link
Author

Usage while building retrofit instance.

private val retrofit = Retrofit.Builder() .baseUrl(BuildConfig.API_BASE_URL) .addConverterFactory(GsonConverterFactory.create( GsonBuilder().registerTypeAdapter( OfferType::class.java, EnumJsonAdapter(OfferType.INVALID) ) )) .client(okHttpBuilder.build()) .build()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment