6

Following suggestions in Using Enums while parsing JSON with GSON, I am trying to serialize a map whose keys are an enum using Gson.

Consider the following class:

public class Main {

    public enum Enum { @SerializedName("bar") foo }

    private static Gson gson = new Gson();

    private static void printSerialized(Object o) {
        System.out.println(gson.toJson(o));
    }

    public static void main(String[] args) {
        printSerialized(Enum.foo); // prints "bar"

        List<Enum> list = Arrays.asList(Enum.foo);
        printSerialized(list);    // prints ["bar"]

        Map<Enum, Boolean> map = new HashMap<>();
        map.put(Enum.foo, true);
        printSerialized(map);    // prints {"foo":true}
    }
}

Two questions:

  1. Why does printSerialized(map) print {"foo":true} instead of {"bar":true}?
  2. How can I get it to print {"bar":true}?
Community
  • 1
  • 1
mbroshi
  • 969
  • 8
  • 21

1 Answers1

13

Gson uses a dedicated serializer for Map keys. This, by default, use the toString() of the object that's about to be used as a key. For enum types, that's basically the name of the enum constant. @SerializedName, by default for enum types, will only be used when serialized the enum as a JSON value (other than a pair name).

Use GsonBuilder#enableComplexMapKeySerialization to build your Gson instance.

private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724