Java : Json with duplicate keys to map using Jackson

天涯浪子 提交于 2021-02-08 15:43:51

问题


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?


回答1:


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




回答2:


Answering since a related question was marked duplicate but seems to address the reverse problem where JSON with duplicate keys needs to be created. So that is Java Model -> JSON with duplicate keys.

Simplest way I found was to implement a custom serializer.

public class CustomSerializer extends StdSerializer<ModelToSerialize> {


    public CustomSerializer(Class<ModelToSerialize> t) {
        super(t);
    }

    @Override
    public void serialize(ModelToSerialize value, com.fasterxml.jackson.core.JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("DuplicateJsonKey", value.getDup1());
        gen.writeStringField("DuplicateJsonKey", value.getDup2());
        // Map all other values on value that you want to be present in the JSON
        gen.writeEndObject();
    }
}

And then when you go to serialize:

SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(ModelToSerialize.class, new CustomSerializer(ModelToSerialize.class));
objectMapper.registerModule(simpleModule);
String sr = objectMapper.writeValueAsString(modelToSerialize);


来源:https://stackoverflow.com/questions/45425276/how-to-allow-duplicate-keys-when-using-jackson-objectmapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!