GSON 递归解码映射键

我想使用 GSON 来解码键不是字符串的映射数组。我知道 JSON 类型不允许将对象用作键,所以我希望 GSON 可以递归工作来解码字符串。


爪哇


public class Reader {

    static class Key {

        int a;

        int b;

    }

    static class Data {

        HashMap<Key, Integer> map;

    }



    public static void read() {

        Gson gson = new Gson();

        String x = "[{\"map\": { \"{\\\"a\\\": 0, \\\"b\\\": 0}\": 1 }}]";

        Data[] y = gson.fromJson(x, Data[].class);

    }

}

JSON 示例


[

    {

        "map": {

            "{\"a\": 0, \"b\": 0}": 1

        }

    }

]

我想在这里实现的是,字符串"{\"a\": 0, \"b\": 0}"被 GSON 解码为一个类型的对象,Key两个成员都设置为 0。然后,该对象可用于填写 Data 类的 HashMap。


这有可能实现吗?


万千封印
浏览 179回答 1
1回答

守候你守候我

您可以使用 custom 来实现这一点JsonDeserializer。使用自定义反序列化器,您可以决定如何反序列化此类Key。在某处实现它,下面的内联示例:public JsonDeserializer<Key> keyDs = new JsonDeserializer<Key>() {&nbsp; &nbsp; private final Gson gson = new Gson();&nbsp;&nbsp; &nbsp; @Override&nbsp; &nbsp; public Key deserialize(JsonElement json, Type typeOfT,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;JsonDeserializationContext context)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throws JsonParseException {&nbsp; &nbsp; &nbsp; &nbsp; // This will be valid JSON&nbsp; &nbsp; &nbsp; &nbsp; String keyJson = json.getAsString();&nbsp; &nbsp; &nbsp; &nbsp; // use another Gson to parse it,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // otherwise you will have infinite recursion&nbsp; &nbsp; &nbsp; &nbsp; Key key = gson.fromJson(keyJson, Key.class);&nbsp; &nbsp; &nbsp; &nbsp; return key;&nbsp; &nbsp; }};注册GsonBuilder,创建Gson和反序列化:Data[] mapPojos = new GsonBuilder().registerTypeAdapter(Key.class, ds).create()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .fromJson(x, Data[].class);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java