遵循 Using Enums while parsing JSON with GSON 中的建议,我正在尝试使用 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}
}
}
两个问题:
- 为什么
printSerialized(map)
打印{"foo":true}
而不是{"bar":true}
?< - 如何让它打印
{"bar":true}
?
最佳答案
Gson 为 Map
键使用了一个专用的序列化器。这在默认情况下使用将要用作键的对象的 toString()
。对于 enum
类型,这基本上就是 enum
常量的名称。 @SerializedName
,默认用于 enum
类型,仅在将 enum
序列化为 JSON 值(而不是对名称)时使用。
使用 GsonBuilder#enableComplexMapKeySerialization
构建您的 Gson
实例。
private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
关于java - 使用带有自定义序列化的 Gson 序列化枚举映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32149138/