Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EnumMap deserialization fails with ClassCastException #2067

Closed
Marcono1234 opened this issue Jan 29, 2022 · 0 comments · Fixed by #2071
Closed

EnumMap deserialization fails with ClassCastException #2067

Marcono1234 opened this issue Jan 29, 2022 · 0 comments · Fixed by #2071
Labels

Comments

@Marcono1234
Copy link
Collaborator

Gson version

e2e851c

Java / Android version

openjdk version "11.0.13" 2021-10-19
OpenJDK Runtime Environment Temurin-11.0.13+8 (build 11.0.13+8)
OpenJDK 64-Bit Server VM Temurin-11.0.13+8 (build 11.0.13+8, mixed mode)

Description

EnumMap deserialization fails with ClassCastException:

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class java.util.EnumMap

The underlying issue is related to #1708, it appears special handling for EnumMap is missing.
(I am a bit surprised that this issue has not been mentioned here anywhere before.)

Reproduction steps

Test case:

private static enum MyEnum {
  VALUE1, VALUE2
}

public void testEnumMap() throws Exception {
  EnumMap<MyEnum, String> map = new EnumMap<MyEnum, String>(MyEnum.class);
  map.put(MyEnum.VALUE1, "test");
  String json = gson.toJson(map);
  assertEquals("{\"VALUE1\":\"test\"}", json);

  Type type = new TypeToken<EnumMap<MyEnum, String>>() {}.getType();
  EnumMap<?, ?> actualMap = gson.fromJson("{\"VALUE1\":\"test\"}", type);
  Map<?, ?> expectedMap = Collections.singletonMap(MyEnum.VALUE1, "test");
  assertEquals(expectedMap, actualMap);
}

Exception stack trace

Not really useful because ClassCastException occurs in user code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant