Java:带有重复键的 Json 使用 Jackson 进行映射 [英] Java : Json with duplicate keys to map using Jackson

查看:33
本文介绍了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 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 进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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