9

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?

Jayaprakash Mara
  • 323
  • 4
  • 11

2 Answers2

14

There is an adapters artifact for extra adapters like EnumJsonAdapter.

https://github.com/square/moshi/tree/master/moshi-adapters#download

Eric Cochran
  • 8,414
  • 5
  • 50
  • 91
  • 3
    I'm new to this kind of nested artifact model. Can you please add a section in the main readme page saying about adapter artifact like it speaks of Kotlin? – Jayaprakash Mara Jan 11 '19 at 13:57
4

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()
MeLean
  • 3,092
  • 6
  • 29
  • 43