JSON 文件 - Java: editing/updating 字段值

JSON File - Java: editing/updating fields values

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

我想要一种有效的方法来更新 json 文件,仅在需要的字段 中使用较新的 JSONObjects 实例的内容。

例如:

我有存档

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?

一般来说,我想更新内容较新(不同)的每个键的值。

其实我的代码是:

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? */
}

你可以这样做:

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...!!");
            }
        }
    }
}