使用jackson将json反序列化为复杂的Map对象 [英] Deserialize json into complex Map object using jackson

查看:1110
本文介绍了使用jackson将json反序列化为复杂的Map对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下json示例

{
    "key1" : {

        "k11":["vala","valb","valc"],
        "k12":["vald"],
        "k13":["vale","valf"]
    },
    "key2" : {

        "key21":["valg","valh","vali"],
        "key22":["valj"],
        "key23":["valk","vall"]
    }
}

这将转换为Map< String,Map< String,List< String >>>。

This translates into a Map<String,Map<String,List<String>>>.

有谁能告诉我如何将此转换为这个复杂的Map对象。我做了一个名为constructMapType的方法,但不确定它是否处理复杂的Map类型。

Could anyone please let me know how i can convert this in this into this complex Map object. I do a a method called constructMapType, but not sure if it handles complex Map type.

推荐答案

似乎与 .constructMapType(Map.class,String.class,Map.class)一起正常工作)

public static void main(String[] args) throws Exception {
    final String json
            = "{\n"
            + "    \"key1\" : {\n"
            + "        \"k11\":[\"vala\",\"valb\",\"valc\"],\n"
            + "        \"k12\":[\"vald\"],\n"
            + "        \"k13\":[\"vale\",\"valf\"]\n"
            + "    },\n"
            + "    \"key2\" : {\n"
            + "        \"key21\":[\"valg\",\"valh\",\"vali\"],\n"
            + "        \"key22\":[\"valj\"],\n"
            + "        \"key23\":[\"valk\",\"vall\"]\n"
            + "    }\n"
            + "}";
    ObjectMapper mapper = new ObjectMapper();

    Map<String, Map<String, List<String>>> map 
            = mapper.readValue(json,TypeFactory.defaultInstance()
                    .constructMapType(Map.class, String.class, Map.class));

    for (String outerKey: map.keySet()) {
        System.out.println(outerKey + ": " + map.get(outerKey));
        for (String innerKey: map.get(outerKey).keySet()) {
            System.out.print(innerKey + ": [");
            for (String listValue: map.get(outerKey).get(innerKey)) {
                System.out.print(listValue + ",");
            }
            System.out.println("]");
        }
    }
}

你可以一路走下去将所有泛型列表下载到列表< String> ,但如上所示,没有必要。但只是为了表明我的意思

You could go all the way down listing all the generics down to the List<String>, but as seen above it isn't necessary. But just to show what I mean

TypeFactory factory = TypeFactory.defaultInstance();
Map<String, Map<String, List<String>>> map 
        = mapper.readValue(json, factory.constructMapType(
                Map.class, 
                factory.constructType(String.class), 
                factory.constructMapType(
                        Map.class, 
                        factory.constructType(String.class), 
                        factory.constructCollectionType(
                                List.class, 
                                String.class))));

这篇关于使用jackson将json反序列化为复杂的Map对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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