小编mbr*_*shi的帖子

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

使用GSON解析JSON时使用Enums中的建议,我正在尝试序列化其键是enum使用Gson 的映射.

考虑以下课程:

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}
    }
}
Run Code Online (Sandbox Code Playgroud)

两个问题:

  1. 为什么printSerialized(map)打印{"foo":true}而不是{"bar":true}
  2. 我怎么才能打印出来{"bar":true}

java enums gson

6
推荐指数
1
解决办法
813
查看次数

标签 统计

enums ×1

gson ×1

java ×1