问题描述
我有一个具有相同键但不同值的 json 文件,如下所示,
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"
}
}
}
来自外部系统.如何将json转成java map对象并访问key的不同值:A
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>>(){});
它返回一个带有唯一键的映射.但我需要一个地图对象来保存 json 文件中的所有数据.
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?
推荐答案
我同意@fge 的评论.
I agree with comments by @fge.
但如果你真的坚持要解决这个问题,你可以继承 HashMap
(或任何其他 Map
),覆盖它的 put
方法,并使用您想要的任何机制处理重复项.只要确保你的 Map
有一个无参数的构造函数.
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 也可能具有允许保留重复项的数据类型(Multimap
?).如果是这样,您将需要使用 Jackson 的 Guava 模块:https://github.com/FasterXML/jackson-datatype-guava
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
这篇关于Java:具有重复键的 Json 使用 Jackson 进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!