【问题标题】:Serializing a map of enums with Gson with custom serialization使用 Gson 和自定义序列化序列化枚举映射
【发布时间】:2015-11-15 22:03:32
【问题描述】:

按照Using Enums while parsing JSON with GSON 中的建议,我正在尝试使用 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<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}

【问题讨论】:

    标签: java enums gson


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-20
      • 2013-07-17
      • 2021-11-28
      • 2014-12-12
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多