Skip to content

Instantly share code, notes, and snippets.

@BramYeh
Created March 28, 2017 13:11
Show Gist options
  • Save BramYeh/b44272a1a53866f129d0df60b1ab28c6 to your computer and use it in GitHub Desktop.
Save BramYeh/b44272a1a53866f129d0df60b1ab28c6 to your computer and use it in GitHub Desktop.
LowercaseEnumTypeAdapterFactory
public class LowercaseEnumTypeAdapterFactory implements TypeAdapterFactory {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<T> rawType = (Class<T>) type.getRawType();
if (!rawType.isEnum()) {
return null;
}
final Map<String, T> lowercaseToConstant = new HashMap<String, T>();
for (T constant : rawType.getEnumConstants()) {
lowercaseToConstant.put(toLowercase(constant), constant);
}
return new TypeAdapter<T>() {
public void write(JsonWriter out, T value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(toLowercase(value));
}
}
public T read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
} else {
return lowercaseToConstant.get(reader.nextString());
}
}
};
}
private String toLowercase(Object o) {
return o.toString().toLowerCase(Locale.US);
}
}
@Papashkin
Copy link

Great solution which helps me. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment