在看到您发布的 json 后,我认为您正在尝试合并两个具有相同 id 但不同元数据 id 的 json。由于 json 对键值起作用。同一个键不能有两个值,例如这个值
"color":"blue", "green",
"id": "84779jh","84ergfujh"
除非你把颜色当作一个数组。看到你的 json 后,你根据元数据 id 创建地图,你可以将这些元数据地图添加到单个元数据地图
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import com.google.common.collect.ImmutableMap;
public class JsonFileMapExample {
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
// read JSON from a file
Map<String, Object> map_json1 = mapper.readValue(new File(
"F:/Work/DB/work/workspace/restclient/src/json1.json"),
new TypeReference<Map<String, Object>>() {
});
Map<String, Object> map_json2 = mapper.readValue(new File("F:/Work/DB/work/workspace/restclient/src/json2.json"),new TypeReference<Map<String, Object>>() { });
System.out.println(map_json1);
System.out.println(map_json2);
Map<String, Object> map2 = (Map<String, Object>) map_json1.get("metadata");
Map<String, Object> map_json3 = new HashMap<String, Object>();
map_json3 = mergeMyTwoMaps((Map<String, Object>) map_json1.get("metadata"),(Map<String, Object>) map_json2.get("metadata"));
System.out.println(map_json3);
} catch (Exception e) {
e.printStackTrace();
}
}
static Map<String, Object> mergeMyTwoMaps(Map<String, Object> map1, Map<String, Object> map2) {
return ImmutableMap.<String, Object>builder()
.putAll(map1)
.putAll(map2)
.build();
}
}
输出:
json1= {id=16875, position=[1, 2, 5, 7], metadata={id=84779jh, color=blue, more={some=randomdata, absolutly=noStructure}}}
json2={id=16875, position=[1, 2, 5, 7], metadata={id=84779jhdf, color=green, more={some=dsfasdf, absolutly=afdsadsf}}}
json3_aftermerged={id=16875, position=[1, 2, 5, 7], metadata={id=84779jh, color=blue, more={some=randomdata, absolutly=noStructure}},{id=16875, position=[1, 2, 5, 7], metadata={id=84779jhdf, color=green, more={some=dsfasdf, absolutly=afdsadsf}}}
注意使用这个你需要有来自http://code.google.com/p/guava-libraries/的 jar 文件