将JSON字符串展平为Map< String,String>使用Gson或Jackson [英] Flatten a JSON string to Map<String, String> using Gson or Jackson

查看:104
本文介绍了将JSON字符串展平为Map< String,String>使用Gson或Jackson的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

{
    "id" : "123",
    "name" : "Tom",
    "class" : {
        "subject" : "Math",
        "teacher" : "Jack"
    }
}

我想获取Map<String, String>:

"id" : "123",
"name" : "Tom",
"subject" : "Math",
"teacher" : "Jack"

推荐答案

我不确定是否有某些东西(谈论Gson).但是,您可以编写自定义递归解串器:

I'm not sure if something exists out of the box (speaking about Gson). However you could write a custom recursive deserializer:

Type t = new TypeToken<Map<String, String>>(){}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(t, new FlattenDeserializer()).create();
Map<String, String> map = gson.fromJson(new FileReader(new File("file")), t);

...

class FlattenDeserializer implements JsonDeserializer<Map<String, String>> {
    @Override
    public Map<String, String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        Map<String, String> map = new LinkedHashMap<>();

        if (json.isJsonArray()) {
            for (JsonElement e : json.getAsJsonArray()) {
                map.putAll(deserialize(e, typeOfT, context));
            }
        } else if (json.isJsonObject()) {
            for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
                if (entry.getValue().isJsonPrimitive()) {
                    map.put(entry.getKey(), entry.getValue().getAsString());
                } else {
                    map.putAll(deserialize(entry.getValue(), typeOfT, context));
                }
            }
        }
        return map;
    }
}

以您的示例输出:

{id="123", name="Tom", subject="Math", teacher="Jack"}

尽管不能解决将键映射到基元数组的情况(因为不可能在Map<String, String>中映射具有多个值的键(除非您可以使用数组的String表示形式或可以返回Map<String, Object>),但它适用于对象数组(假设每个对象都有唯一的键).

although it doesn't handle the case when a key is mapped to an array of primitives (because it's not possible to map a key with multiple values in a Map<String, String> (unless you can take the String representation of the array or that you can return a Map<String, Object>) but it works for an array of objects (given that each object has a unique key).

所以,如果您有:

{
    "id": "123",
    "name": "Tom",
    "class": {
        "keys": [
            {
                "key1": "value1"
            },
            {
                "key2": "value2"
            }
        ],
        "teacher": "Jack"
    }
}

它将输出:

{id="123", name="Tom", key1="value1", key2="value2", teacher="Jack"}

如果需要处理更多案件,则可以根据需要自定义它.

You can customize it as you need if more cases are needed to be handled.

希望有帮助! :)

这篇关于将JSON字符串展平为Map&lt; String,String&gt;使用Gson或Jackson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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