我的工作流程中有一些 JSONObject,并且通过将它们写入 json 文件来存储相同的 JSONObject。
我想要一种有效的方法来更新 json 文件,仅在需要的字段,包含较新的 JSONObjects 实例的内容。
Eg:
我的档案里有
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...!!");
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)