Java : Json with duplicate keys to map using Jackson(Java:具有重复键的 Json 使用 Jackson 进行映射)
问题描述
我有一个具有相同键但不同值的 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 进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:具有重复键的 Json 使用 Jackson 进行映射


基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01