使用Gson与自定义序列化序列化枚举映射 [英] Serializing a map of enums with Gson with custom serialization
问题描述
遵循在使用GSON解析JSON时使用枚举中的建议,我试图序列化一个映射,其键是 enum
使用Gson。
Following suggestions in Using Enums while parsing JSON with GSON, I am trying to serialize a map whose keys are an enum
using Gson.
考虑以下课程:
Consider the following class:
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}
}
}
问题:
$ b
Two questions:
- 为什么
printSerialized(map) print
{foo:true}
代替{bar:true}
? - 我得到它打印
{bar:true}
?
- Why does
printSerialized(map)
print{"foo":true}
instead of{"bar":true}
? - How can I get it to print
{"bar":true}
?
推荐答案
Gson为 Map
键使用专用序列化程序。这在默认情况下使用将要用作键的对象的 toString()
。对于 enum
类型,基本上是 enum
常量的名称。 @SerializedName
,默认用于 enum
类型,只有在序列化 enum
作为JSON值(除配对名称外)。
Gson uses a dedicated serializer for Map
keys. This, by default, use the toString()
of the object that's about to be used as a key. For enum
types, that's basically the name of the enum
constant. @SerializedName
, by default for enum
types, will only be used when serialized the enum
as a JSON value (other than a pair name).
使用 GsonBuilder#enableComplexMapKeySerialization
构建您的 Gson
实例。
private static Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
这篇关于使用Gson与自定义序列化序列化枚举映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!