我正在构建一个更新我的应用程序的updater工具。 我需要保存以前版本的配置文件。 一些配置文件是JSON文件。 有没有办法以我保留旧值的方式更新JSON文件 但如果有新的物品或钥匙,他们也会被保存吗?
例如: 版本1 json文件:
{
"name": "demo",
"description": "Parse some JSON data",
"location": "New York"
}
版本2 json文件:
{
"name": "demo",
"description": "Parse some JSON data",
"location": "London",
"day": "Monday"
}
合并后的预期json文件:
{
"name": "demo",
"description": "Parse some JSON data",
"location": "New York",
"day": "Monday"
}
有没有办法在没有任何外部库的情况下这样做?
答案 0 :(得分:2)
正如@ cricket_007所建议的,这个解决方案对我有用:
public void mergeJsonsFiles(File newJson, File oldJson) throws Exception {
HashMap<String, Object> newMap = convertJsonToMap(newJson);
HashMap<String, Object> oldMap = convertJsonToMap(oldJson);
for (Entry<String, Object> entry : oldMap.entrySet()) {
if (newMap.get(entry.getKey()) == null) {
newMap.put(entry.getKey(), entry.getValue());
}
}
ObjectMapper mapper = new ObjectMapper();
String jsonFromMap = mapper.writeValueAsString(newMap);
PrintWriter writer = new PrintWriter(newJson);
writer.write(jsonFromMap);
writer.close();
}
private HashMap<String, Object> convertJsonToMap(File json) {
ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> map = new HashMap<String, Object>();
try {
map = mapper.readValue(json, new TypeReference<HashMap<String, Object>>(){});
} catch (IOException e) {
map.clear();
}
return map;
}