GSON递归解码映射密钥 [英] GSON recursively decode map keys

查看:124
本文介绍了GSON递归解码映射密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use GSON to decode an array of maps in which the keys are not Strings. I know that the JSON type does not allow for objects to be used as keys, so I was hoping it is possible to have GSON work recursively to decode Strings.

Java

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.然后,该对象可用于填写HashMap的HashMap.数据类.

What I would like to achieve here, is that the string "{\"a\": 0, \"b\": 0}" is decoded by GSON to an object of type Key with both members set to 0. Then, that object could be used to fill out the HashMap of the Data class.

这有可能实现吗?

推荐答案

您可以使用自定义JsonDeserializer来实现.使用自定义反序列化器,您可以决定如何对此类Key进行反序列化.在下面的内联示例中实现它:

You can achieve this with custom JsonDeserializer. With a custom deserializer you can decide howto deserialize this class Key. Implement it somewhere, inline example below:

public JsonDeserializer<Key> keyDs = new JsonDeserializer<Key>() {
    private final Gson gson = new Gson(); 
    @Override
    public Key deserialize(JsonElement json, Type typeOfT,
                               JsonDeserializationContext context)
            throws JsonParseException {
        // This will be valid JSON
        String keyJson = json.getAsString();
        // use another Gson to parse it, 
        // otherwise you will have infinite recursion
        Key key = gson.fromJson(keyJson, Key.class);
        return key;
    }
};

GsonBuilder注册,创建Gson并反序列化:

Register it with GsonBuilder, create Gson and deserialize:

Data[] mapPojos = new GsonBuilder().registerTypeAdapter(Key.class, ds).create()
            .fromJson(x, Data[].class);

这篇关于GSON递归解码映射密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆