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

我的工作流程中有一些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...!!");

}

}

}

}

以上是 JSON文件-Java:编辑/更新字段值 的全部内容, 来源链接: utcz.com/qa/406139.html

回到顶部