java的map有putAll来合并两个map,但是只能做到第一层的合并,如果多层级就不行,使用递归做一个合并map简单方法
to_map
{
"a":"aaa",
"b":"bbb",
"c":{
"c1":"ccc1",
"c2":{
"c11":"c1c1c1"
},
"c3":"ccc3"
}
}
from_map
{
"b":"bbb_new",
"c":{
"c1":"ccc1_new",
"c3":{
"c11":"c1c1c1"
},
"c4":"ccc4"
},
"d":"d_new"
}
合并后to_map的效果
{
"a": "aaa",
"b": "bbb_new",
"c":
{
"c1": "ccc1_new",
"c2":
{
"c11": "c1c1c1"
},
"c3":
{
"c11": "c1c1c1"
},
"c4": "ccc4"
},
"d": "d_new"
}
java代码
public class Test {
public static void mergeMap(Map<String, Object> to, Map<String, Object> from){
Set<Map.Entry<String, Object>> entries = to.entrySet();
Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
while (iterator.hasNext()){
Map.Entry<String, Object> kv = iterator.next();
String toKey = kv.getKey();
Object toValue = kv.getValue();
Object fromValue = from.get(toKey);
if(fromValue != null){
if(toValue instanceof Map){
Map<String, Object> childTo = (Map<String, Object>)toValue;
mergeMap(childTo, (Map<String, Object>) fromValue);
}else{
to.put(toKey,fromValue);
}
}
}
Set<String> keys = from.keySet();
for (String key : keys) {
if (!to.containsKey(key)){
to.put(key,from.get(key));
}
}
}
public static void main(final String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
Map to = objectMapper.readValue("{\"a\":\"aaa\",\"b\":\"bbb\",\"c\":{\"c1\":\"ccc1\",\"c2\":{\"c11\":\"c1c1c1\"},\"c3\":\"ccc3\"}}", Map.class);
Map from = objectMapper.readValue("{\"b\":\"bbb_new\",\"c\":{\"c1\":\"ccc1_new\",\"c3\":{\"c11\":\"c1c1c1\"},\"c4\":\"ccc4\"},\"d\":\"d_new\"}", Map.class);
mergeMap(to,from);
System.out.println(objectMapper.writeValueAsString(to));;
}
}