使用Gson进行枚举类型的Map序列化和自定义序列化

7

按照使用GSON解析JSON时使用枚举类型的建议,我试图使用Gson序列化一个键为enum的map。

考虑下面这个类:

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个回答

14

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

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

private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接