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

时间:2016-06-26 18:40:54

标签: java json mapping editing

我的工作流中有一些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? */
}

2 个答案:

答案 0 :(得分:4)

你可以这样做:

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

答案 1 :(得分:0)

Underscore-java可以编辑json文件。我是该项目的维护者。 Live example

import com.github.underscore.lodash.U;

public class MyClass {
    public static void main(String args[]) {
        String json = "{\"key1\":\"val1\", \"key2\":\"val2\"}";
        java.util.Map<String, Object> object = (java.util.Map<String, Object>) U.fromJson(json);
        U.set(object, "key1", "val1_newer");
        U.set(object, "key2", "val2_newer");
        System.out.println(U.toJson(object)); 
    }
}

// {
//   "key1": "val1_newer",
//   "key2": "val2_newer"
// }