JSON 文件 - Java:编辑/更新字段值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38041893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:57:01  来源:igfitidea点击:

JSON File - Java: editing/updating fields values

javajsonmappingediting

提问by GrayFox

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

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

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

我想要一种有效的方法来更新 json 文件,只有需要的字段,以及较新的 JSONObjects 实例的内容。

Eg:

例如:

On file I have

在文件中我有

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

In memory I have

在记忆中我有

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

The update will be like:

更新将类似于:

 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).

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

Actually my code is:

其实我的代码是:

import org.json.JSONObject;
import com.fasterxml.Hymanson.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? */
}

采纳答案by PVR

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