Java : Json with duplicate keys to map using Jackson

喜你入骨 提交于 2020-01-10 04:14:06

问题


I have a json file with same key but different values as follows,

{
    "domains" : {
        "A" : {
            "name" : "a",
            "type" : "a1"
        },
        "B"  :{
            "name" : "r",
            "type" : "g1"
         },
        "A" : {
           "name" : "b",
           "type" : "b1"
        }
    }
}

which is coming from external system. How to convert the json to java map object and access the different values of the key: A

I am using something like below,

map = mapper.readValue(json, new TypeReference<HashMap<String,String>>(){});

which returns a map with unique keys. But I need a map object to hold all the data from json file.

Anyway to achieve this?


回答1:


I agree with comments by @fge.

But if you really insists on solving this, you could sub-class HashMap (or any other Map), override its put method, and handle duplicates using whatever mechanism you want. Just make sure your Map has a no-arguments constructor.

Guava may also have a datatype that would allow retaining duplicates (Multimap?). If so, you will want to use Jackson's Guava module: https://github.com/FasterXML/jackson-datatype-guava



来源:https://stackoverflow.com/questions/27710471/java-json-with-duplicate-keys-to-map-using-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!