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

mbr*_*shi 6 java enums gson

使用GSON解析JSON时使用Enums中的建议,我正在尝试序列化其键是enum使用Gson 的映射.

考虑以下课程:

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}
    }
}
Run Code Online (Sandbox Code Playgroud)

两个问题:

  1. 为什么printSerialized(map)打印{"foo":true}而不是{"bar":true}
  2. 我怎么才能打印出来{"bar":true}

Sot*_*lis 11

Gson使用专用的序列化器来实现Map密钥.默认情况下,这toString()将使用即将用作键的对象.对于enum类型,这基本上是enum常量的名称.@SerializedName默认情况下,enum类型仅在序列化为enumJSON值时使用(除了对名称).

使用GsonBuilder#enableComplexMapKeySerialization来构建你的Gson实例.

private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
Run Code Online (Sandbox Code Playgroud)