Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save johnjohndoe/de1233238c2180a43f584e1f1eb28d61 to your computer and use it in GitHub Desktop.
Save johnjohndoe/de1233238c2180a43f584e1f1eb28d61 to your computer and use it in GitHub Desktop.
An enum JsonAdapter for Moshi that allows for a fallback value when deserializing unknown strings. NOTE: Allows null for the default. https://github.com/square/moshi/blob/master/moshi-adapters/src/main/java/com/squareup/moshi/adapters/EnumJsonAdapter.kt
import com.squareup.moshi.Json;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.JsonReader;
import com.squareup.moshi.JsonWriter;
import java.io.IOException;
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(constant.name()).getAnnotation(Json.class);
String name = annotation != null ? annotation.name() : constant.name();
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];
reader.nextString();
return defaultValue;
}
@Override public void toJson(JsonWriter writer, T value) throws IOException {
writer.value(nameStrings[value.ordinal()]);
}
@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