Gson Serializetion Bug in Enum Map
- Dominant language
- Java
- Stars
- 24.2k
- Forks
- 4.5k
- Avg merge
- 6d 4h
- Merged PRs (30d)
- 12
Description
When the enum type is used as the key of one map, if there is `@SerializedName("name")` at the declaration of the enum items, the Gson serialization and deserialization do NOT work well.
Following is the bad case
```java
import com.google.gson.annotations.SerializedName;
public enum RoomIdentifier {
@SerializedName("MARKER_NAME") // Here is the bad case
ROOM_NAME;
}
```
Test code is here
```java
public void testConvert() {
RoomIdentifier id = RoomIdentifier.ROOM_NAME;
Map slots = new HashMap();
slots.put(RoomIdentifier.ROOM_NAME,"ROOM_NAME_TEST");
String strSerialized = gson.toJson(slots);
Type type = new TypeToken>() {
}.getType();
Map slotsDeserialized = gson.fromJson(strSerialized, type);
System.out.println(gson.toJson(id)); // "MARKER_NAME" //As expect, SerializedName is used
System.out.println(strSerialized); // {"ROOM_NAME":"ROOM_NAME_TEST"} // the key name is not SerializedName
System.out.println(slotsDeserialized); // {null=ROOM_NAME_TEST} //The key is null
}
```
**Root cause**
- In the serialization function `GSON::toJson` , the **MapTypeAdapterFactory::Adapter** uses `String.valueOf(entry.getKey())` to generate the key. `@SerializedName("name")` ("MARKER_NAME" in the example) is NOT used at all. Here is Gson [code](https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java#L207)
- But in the deserialization function `GSON::fromJson` , **EnumTypeAdapter** is used to deserialize the key(here is [code](https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java)). If one field is marked by `@SerializedName("name")` , the original name string ("ROOM_NAME" in the example ) could NOT be recognized, `null` is returned.
Contributor guide
Assessment
This issue has not been assessed yet.