Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
An enum JsonAdapter for Moshi that allows for a fallback value when deserializing unknown strings. NOTE: Allows null for the default.
import com.squareup.moshi.Json;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.JsonReader;
import com.squareup.moshi.JsonWriter;
public final class EnumWithDefaultValueJsonAdapter<T extends Enum<T>> extends JsonAdapter<T> {
private final Class<T> enumType;
private final String[] nameStrings;
private final T[] constants;
private final JsonReader.Options options;
private final T defaultValue;
public EnumWithDefaultValueJsonAdapter(Class<T> enumType, T defaultValue) {
this.enumType = enumType;
this.defaultValue = defaultValue;
try {
constants = enumType.getEnumConstants();
nameStrings = new String[constants.length];
for (int i = 0; i < constants.length; i++) {
T constant = constants[i];
Json annotation = enumType.getField(;
String name = annotation != null ? :;
nameStrings[i] = name;
options = JsonReader.Options.of(nameStrings);
} catch (NoSuchFieldException e) {
throw new AssertionError(e);
@Override public T fromJson(JsonReader reader) throws IOException {
int index = reader.selectString(options);
if (index != -1) return constants[index];
return defaultValue;
@Override public void toJson(JsonWriter writer, T value) throws IOException {
@Override public String toString() {
return "JsonAdapter(" + enumType.getName() + ").defaultValue( " + defaultValue + ")";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment