Parsing Map<Enum,Obj> - 501 (#1950)

* Added parsing support for enum that has overridden toString() method.

* Fix a tiny formatting problem

* Fixed formatting issue

Co-authored-by: Éamonn McManus <emcmanus@google.com>
This commit is contained in:
Mahmut H. Kocas 2022-02-22 00:11:43 +03:00 committed by GitHub
parent 49ddab9eeb
commit 7ee3e2787f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -775,6 +775,7 @@ public final class TypeAdapters {
private static final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
private final Map<String, T> nameToConstant = new HashMap<String, T>();
private final Map<String, T> stringToConstant = new HashMap<String, T>();
private final Map<T, String> constantToName = new HashMap<T, String>();
public EnumTypeAdapter(final Class<T> classOfT) {
@ -801,6 +802,8 @@ public final class TypeAdapters {
@SuppressWarnings("unchecked")
T constant = (T)(constantField.get(null));
String name = constant.name();
String toStringVal = constant.toString();
SerializedName annotation = constantField.getAnnotation(SerializedName.class);
if (annotation != null) {
name = annotation.value();
@ -809,6 +812,7 @@ public final class TypeAdapters {
}
}
nameToConstant.put(name, constant);
stringToConstant.put(toStringVal, constant);
constantToName.put(constant, name);
}
} catch (IllegalAccessException e) {
@ -820,7 +824,9 @@ public final class TypeAdapters {
in.nextNull();
return null;
}
return nameToConstant.get(in.nextString());
String key = in.nextString();
T constant = nameToConstant.get(key);
return (constant == null) ? stringToConstant.get(key) : constant;
}
@Override public void write(JsonWriter out, T value) throws IOException {
@ -928,4 +934,4 @@ public final class TypeAdapters {
}
};
}
}
}