使用Gson使用自定义序列化序列化枚举映射

时间:2015-08-21 20:57:13

标签: java enums gson

根据Using Enums while parsing JSON with GSON中的建议,我正在尝试使用Gson序列化其键为enum的地图。

考虑以下课程:

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}
    }
}

两个问题:

  1. 为什么printSerialized(map)打印{"foo":true}而不是{"bar":true}
  2. 如何让它打印{"bar":true}

1 个答案:

答案 0 :(得分:9)

Gson使用Map密钥的专用序列化程序。默认情况下,这会使用即将用作键的对象的toString()。对于enum类型,它基本上是enum常量的名称。默认情况下,@SerializedName类型的enum仅在将enum序列化为JSON值(对名称除外)时使用。

使用GsonBuilder#enableComplexMapKeySerialization构建您的Gson实例。

private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
相关问题