使用Gson使用自定义序列化序列化枚举映射
按照使用GSON解析JSON时使用枚举的建议,我试图使用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 list = Arrays.asList(Enum.foo); printSerialized(list); // prints ["bar"] Map map = new HashMap(); map.put(Enum.foo, true); printSerialized(map); // prints {"foo":true} } }
两个问题:
- 为什么
printSerialized(map)
print{"foo":true}
而不是{"bar":true}
? - 如何打印
{"bar":true}
?
Gson为Map
键使用专用的序列化器。 默认情况下,这使用将要用作键的对象的toString()
。 对于enum
类型,它基本上是enum
常量的名称。 默认情况下,对于enum
类型, @SerializedName
仅在将enum
序列化为JSON值(除了对名称)时使用。
使用GsonBuilder#enableComplexMapKeySerialization
来构建您的Gson
实例。
private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();