问题
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