Java-合并JSON文件 [英] Java - Merge JSON files

查看:344
本文介绍了Java-合并JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个更新程序实用程序,用于更新我的应用程序. 我需要保存以前版本的配置文件. 一些配置文件是JSON文件. 有没有办法以保持旧值的方式更新JSON文件 但是如果有新的对象或键,它们也会被保存吗?

I am building an updater util that update my application. I need to save my configuration files from the previous version. Some of the configurations files are JSON files. Is there a way to update the JSON files in a way that i'm keeping the old values but if there new objects or keys they will be saved also?

例如: 版本1 json文件:

For example: Version 1 json file:

{
    "name": "demo",
    "description": "Parse some JSON data",
    "location": "New York"
}

第2版json文件:

{
    "name": "demo",
    "description": "Parse some JSON data",
    "location": "London",
    "day": "Monday"
}

合并后的预期json文件:

Expected json file after the merge:

{
    "name": "demo",
    "description": "Parse some JSON data",
    "location": "New York",
    "day": "Monday"
}

有没有没有任何外部库的方法?

Is there a way to do so without any external library?

推荐答案

按照@ cricket_007的建议,此解决方案对我有用:

As @cricket_007 advised, This solution worked for me:

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;
}

这篇关于Java-合并JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆