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 进行映射
基础教程推荐
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Maven:无效的目标版本:10 2022-01-01
