I have an enum class and would like it to fallback to a specific enum value if values don't match any of them. I found a Moshi issue that talks about using EnumJsonAdapter but I don't see any public class for me to use.
I'm using Moshi 1.8.0
Any ideas on how to achieve this or is writing a custom JSON adapter the only way to go?
There is an adapters artifact for extra adapters like EnumJsonAdapter.
https://github.com/square/moshi/tree/master/moshi-adapters/src/main/java/com/squareup/moshi/adapters
I created this generic object to create EnumJsonAdaprters:
object NullableEnumMoshiConverter {
fun <T : Enum<T>> create(enumType: Class<T>, defaultValue: T? = null): JsonAdapter<T> =
EnumJsonAdapter.create(enumType)
.withUnknownFallback(defaultValue)
.nullSafe()
}
It handles null values in the JSON as well. You should Add it in the builder method like this:
Moshi.Builder().apply {
with(YourEnumClassName::class.java) {
add(this, NullableEnumMoshiConverter.create(this))
}
}.build()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With