Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fallback on a enum if values don't match in Moshi

Tags:

enums

moshi

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?

like image 751
Jayaprakash Mara Avatar asked Dec 23 '22 01:12

Jayaprakash Mara


2 Answers

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

like image 89
Eric Cochran Avatar answered Jan 18 '23 10:01

Eric Cochran


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()
like image 22
MeLean Avatar answered Jan 18 '23 11:01

MeLean