在文件的json数组中添加记录

时间:2018-08-28 18:43:46

标签: java json spring

我有一个像这样的json数组

[
    {"submitted":"Bob","limit":0,"ID":123,"target":3},
    {"submitted":"Kate","limit":500,"ID":3221,"target":2}
 ]

我需要找到一种方法,如何在不覆盖文件的情况下将记录插入该文件,或将所有内容加载到内存中

目前我正在这样做

 try (FileWriter file = new FileWriter("C:/test/output.json", true);
         BufferedWriter bfile = new BufferedWriter(file);
         PrintWriter outFile = new PrintWriter(bfile))
    {
        outFile.write(obj.toJSONString()+System.lineSeparator());
        outFile.flush();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:3)

您可以使用org.json读写json对象和数组,如下所示。但我不确定是否可以编辑json文件而不将其读入内存。

package yourPackage;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) throws IOException {
        JSONArray root = new JSONArray(new String(Files.readAllBytes(Paths.get("test.json"))));

        JSONObject obj = new JSONObject();
        obj.put("submitted","");
        obj.put("limit", 0);
        obj.put("ID", 123);
        obj.put("target", 3);

        root.put(obj);

        Files.write(Paths.get("test.json"), root.toString().getBytes());
    }
}

org.json的maven依赖项:

    <!-- https://mvnrepository.com/artifact/org.json/json -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180130</version>
    </dependency>