Skip to content

Commit

Permalink
Parsing Map<Enum,Obj> - 501 (#1950)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
TheDoctorOne and eamonnmcmanus committed Feb 21, 2022
1 parent 49ddab9 commit 7ee3e27
Showing 1 changed file with 8 additions and 2 deletions.
Expand Up @@ -775,6 +775,7 @@ public void write(JsonWriter out, Locale value) throws IOException {

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) {
Expand All @@ -801,6 +802,8 @@ public EnumTypeAdapter(final Class<T> classOfT) {
@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();
Expand All @@ -809,6 +812,7 @@ public EnumTypeAdapter(final Class<T> classOfT) {
}
}
nameToConstant.put(name, constant);
stringToConstant.put(toStringVal, constant);
constantToName.put(constant, name);
}
} catch (IllegalAccessException e) {
Expand All @@ -820,7 +824,9 @@ public EnumTypeAdapter(final Class<T> classOfT) {
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 {
Expand Down Expand Up @@ -928,4 +934,4 @@ public static <T1> TypeAdapterFactory newTypeHierarchyFactory(
}
};
}
}
}

0 comments on commit 7ee3e27

Please sign in to comment.