我想合并两个结构相似的地图:
这是第一张地图
{
"Profile": {
"Location":
{
"City": "Some City",
"State": "Some State",
"Country": "USA"
}
},
"TimeLine": {
"LifeEvents": {
"EventName": "Got Married",
"Date": "15-01-2000"
}
}
}
第二张地图是:
{
"Profile": {
"Office": {
"City": "New City",
"State": "New State",
"Country": "UK"
}
},
"TimeLine": {
"LifeEvents": {
"EventName": "Got Engaged",
"Date": "15-01-1999"
}
}
}
合并后,我希望它采用以下格式:
{
"Profile": {
"Office": {
"City": "New City",
"State": "New State",
"Country": "UK"
},
"Location": {
"City": "Some City",
"State": "Some State",
"Country": "USA"
}
},
"TimeLine": {
"LifeEvents": [
{
"EventName": "Got Engaged",
"Date": "15-01-1999"
},
{
"EventName": "Got Married",
"Date": "15-01-2000"
}
]
}
}
我尝试的解决方案是:
private static Map merge(Map original, Map newMap) {
for (Object key : newMap.keySet())
{
if (newMap.get(key) instanceof Map && original.get(key) instanceof Map)
{
Map originalChild = (Map) original.get(key);
Map newChild = (Map) newMap.get(key);
original.put(key, merge(originalChild, newChild));
}
else if (newMap.get(key) instanceof List && original.get(key) instanceof List)
{
List originalChild = (List) original.get(key);
List newChild = (List) newMap.get(key);
for (Object each : newChild)
{
if (!originalChild.contains(each))
{
originalChild.add(each);
}
}
} else
{
if(!original.containsKey(key)){
original.put(key, newMap.get(key));
}
}
}
return original;
}
我有什么建议可以修改上面的方法来处理我的要求吗?虽然上面给出的Map的结构是JSON格式,但假设你将获得Map作为merge方法的输入。我正在使用new Gson().fromJson(map1String, Map.class);
将JSON转换为Map。