Forked from NightlyNexus/EnumWithDefaultValueJsonAdapter.java
Last active
March 24, 2022 08:27
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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