Class EnumJsonAdapter<T extends Enum<T>>

java.lang.Object
com.squareup.moshi.JsonAdapter<T>
com.squareup.moshi.adapters.EnumJsonAdapter<T>

public final class EnumJsonAdapter<T extends Enum<T>> extends com.squareup.moshi.JsonAdapter<T>
A JsonAdapter for enums that allows having a fallback enum value when a deserialized string does not match any enum value. To use, add this as an adapter for your enum type on your Moshi.Builder:

 Moshi moshi = new Moshi.Builder()
     .add(CurrencyCode.class, EnumJsonAdapter.create(CurrencyCode.class)
         .withUnknownFallback(CurrencyCode.USD))
     .build();
 
  • Nested Class Summary

    Nested classes/interfaces inherited from class com.squareup.moshi.JsonAdapter

    com.squareup.moshi.JsonAdapter.Factory
  • Method Summary

    Modifier and Type
    Method
    Description
    static <T extends Enum<T>>
    EnumJsonAdapter<T>
    create(Class<T> enumType)
     
    fromJson(com.squareup.moshi.JsonReader reader)
     
    void
    toJson(com.squareup.moshi.JsonWriter writer, T value)
     
     
    withUnknownFallback(T fallbackValue)
    Create a new adapter for this enum with a fallback value to use when the JSON string does not match any of the enum's constants.

    Methods inherited from class com.squareup.moshi.JsonAdapter

    failOnUnknown, fromJson, fromJson, fromJsonValue, indent, lenient, nonNull, nullSafe, serializeNulls, toJson, toJson, toJsonValue

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
  • Method Details

    • create

      public static <T extends Enum<T>> EnumJsonAdapter<T> create(Class<T> enumType)
    • withUnknownFallback

      public EnumJsonAdapter<T> withUnknownFallback(@Nullable T fallbackValue)
      Create a new adapter for this enum with a fallback value to use when the JSON string does not match any of the enum's constants. Note that this value will not be used when the JSON value is null, absent, or not a string. Also, the string values are case-sensitive, and this fallback value will be used even on case mismatches.
    • fromJson

      @Nullable public T fromJson(com.squareup.moshi.JsonReader reader) throws IOException
      Specified by:
      fromJson in class com.squareup.moshi.JsonAdapter<T extends Enum<T>>
      Throws:
      IOException
    • toJson

      public void toJson(com.squareup.moshi.JsonWriter writer, T value) throws IOException
      Specified by:
      toJson in class com.squareup.moshi.JsonAdapter<T extends Enum<T>>
      Throws:
      IOException
    • toString

      public String toString()
      Overrides:
      toString in class Object