首页 > 解决方案 > Json 对象保存为 String 而不是 Object

问题描述

我正在使用 Json/Gson 保存和加载哈希图。

当我使用键 String 和 Value EnumElement 保存哈希图属性时。例如:

private static enum Rank {
    BOSS;
}

public static void main(String[] args){

    HashMap<Object, Object> attributes = new HashMap<>();

    attributes.put("test", Rank.BOSS);

    //save json file here...


}

然后在使用 json 加载 hashmap 时,并像这样设置地图:

attributes = loadJson("path/savedAttributes");

然后加载的地图已经把Rank.BOSS的枚举元素改成了String“BOSS”

结果现在是:

 "attributes": {
    "test": "BOSS",
 },

它现在是一个字符串。

我该如何克服呢?

我希望它再次加载为枚举元素而不是字符串表示

标签: javajsonoopgson

解决方案


尝试在TypeAdapterFactory 这里使用 Gson


推荐阅读