I'm working on a nice solution to internationalize Enums
by Gson deserialize (.toJson).
For now I have it:
private static final class GenericEnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
private ResourceBundle bundle = ResourceBundle.getBundle("Messages");
private Class<T> classOfT;
public GenericEnumTypeAdapter(Class<T> classOfT) {
this.classOfT = classOfT;
}
public T read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
return Enum.valueOf(classOfT, in.nextString());
}
public void write(JsonWriter out, T value) throws IOException {
out.value(value == null ? null : bundle.getString("enum." + value.getClass().getSimpleName() + "."
+ value.name()));
}
}
The problem of this solution is: For each enum you should register a new Adapter:
gsonBuilder.registerTypeAdapter(EventSensorState.class,
new GenericEnumTypeAdapter<>(FirstEnum.class)
Do someone has an idea to do it better?