Created
January 4, 2022 12:07
-
-
Save iambaljeet/450365c5b998410ef1be1e4de358ee4a to your computer and use it in GitHub Desktop.
Custom Adapter for setting default value for enums insude API response.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()