JSON文件-Java:编辑/更新字段值 [英] JSON File - Java: editing/updating fields values

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

问题描述

我的工作流程中有一些JSONObject,并且通过将它们写入json文件来存储相同的JSONObject.

I have some JSONObject(s) in my workflow, and the same JSONObjects are stored by writting them into a json file.

我想要一种有效的方法来更新JSON文件,仅在需要的地方添加,并使用更新的JSONObjects实例的内容.

I would like an efficient way to update the json file, only fields where is needed, with the content of newer JSONObjects instances.

例如:

我有档案

ObjectOnFile = {key1:val1, key2:val2,...}

内存中有

ObjectInMemory = {key1:val1_newer, key2:val2_newer,...}

更新将类似于:

 if (!(ObjectInMemory.get(key1).equals(ObjectOnFile.get(key1)))
       // update file field value <--- how to?

通常,我想更新每个键的内容较新(不同)的值.

In general I would like to update the value of every key where its content is newer (different).

实际上我的代码是:

import org.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
Sting key = "key1"; //whatever
JSONObject jo = new JSONObject("{key1:\"val1\", key2:\"val2\"}");
JSONObject root = mapper.readValue(new File(json_file), JSONObject.class);
JSONObject val_newer = jo.getJSONObject(key);
JSONObject val_older = root.getJSObject(key);
if(!val_newer.equals(val_older)){
   root.put(key,val_newer);
/*write back root to the json file...how? */
}

推荐答案

只需执行以下操作即可:

Simply you can do like this:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import com.fasterxml.jackson.databind.ObjectMapper;


public class Test {

    public static void main(String[] args) throws JSONException, IOException 
    {
        ObjectMapper mapper = new ObjectMapper();
        String key = "key1"; //whatever

        JSONObject jo = new JSONObject("{key1:\"val1\", key2:\"val2\"}");
        //Read from file
        JSONObject root = mapper.readValue(new File("json_file"), JSONObject.class);

        String val_newer = jo.getString(key);
        String val_older = root.getString(key);

        //Compare values
        if(!val_newer.equals(val_older))
        {
          //Update value in object
           root.put(key,val_newer);

           //Write into the file
            try (FileWriter file = new FileWriter("json_file")) 
            {
                file.write(root.toString());
                System.out.println("Successfully updated json object to file...!!");
            }
        }
    }
}

这篇关于JSON文件-Java:编辑/更新字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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