Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow duplicate keys when using Jackson ObjectMapper [duplicate]

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?

like image 366
user1321824 Avatar asked Nov 18 '22 13:11

user1321824


2 Answers

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

like image 104
StaxMan Avatar answered Nov 21 '22 03:11

StaxMan


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);
like image 21
BillD Avatar answered Nov 21 '22 05:11

BillD