简体   繁体   English

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

[英]Serializing a map of enums with Gson with custom serialization

Following suggestions in Using Enums while parsing JSON with GSON , I am trying to serialize a map whose keys are an enum using Gson. 按照使用GSON解析JSON时使用枚举的建议,我尝试使用Gson序列化其键是enum的映射。

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}
    }
}

Two questions: 两个问题:

  1. Why does printSerialized(map) print {"foo":true} instead of {"bar":true} ? 为什么printSerialized(map) print {"foo":true}而不是{"bar":true}
  2. How can I get it to print {"bar":true} ? 如何打印{"bar":true}

Gson uses a dedicated serializer for Map keys. Gson为Map键使用专用的序列化器。 This, by default, use the toString() of the object that's about to be used as a key. 默认情况下,这使用将要用作键的对象的toString() For enum types, that's basically the name of the enum constant. 对于enum类型,它基本上是enum常量的名称。 @SerializedName , by default for enum types, will only be used when serialized the enum as a JSON value (other than a pair name). 默认情况下,对于enum类型, @SerializedName仅在将enum序列化为JSON值(除了对名称)时使用。

Use GsonBuilder#enableComplexMapKeySerialization to build your Gson instance. 使用GsonBuilder#enableComplexMapKeySerialization来构建您的Gson实例。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM