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

查看:163
本文介绍了Java:带有重复键的Json使用Jackson进行映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json文件,它具有相同的键值,但值不同,如下所示:

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

来自外部系统
如何将 json转换为java map 对象并访问该键的不同值:A



我正在使用类似下面,

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

这将返回具有唯一键的映射。但是我需要一个map对象来保存来自json文件的所有数据。

无论如何要实现这一点?

解决方案

我同意@fge的评论。



但是,如果你真的坚持解决这个问题,你可以将子类 HashMap (或任何其他的 Map ),覆盖它的 put 方法,使用任何你想要的机制处理重复。只要确保你的 Map 具有一个无参数构造函数。



Guava也可以有一个数据类型,重复( Multimap ?)。如果是这样,你会想要使用杰克逊的Guava模块: https://github.com/FasterXML/jackson -datatype-guava


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?

解决方案

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

这篇关于Java:带有重复键的Json使用Jackson进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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