Created
March 28, 2017 13:11
-
-
Save BramYeh/b44272a1a53866f129d0df60b1ab28c6 to your computer and use it in GitHub Desktop.
LowercaseEnumTypeAdapterFactory
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
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great solution which helps me. Thank you!