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

标签 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();
    }

最佳答案

您可以使用 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>

关于java - 在文件中的json数组中添加记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52064428/

相关文章:

javascript - Angular 2 调用 Web Api 时未显示 json 结果

python - django orm 组按 json 字段中的 json 键

android - Android Studio:找不到MessageSource的ResourceBundle [messages]:找不到基本名称消息的包,语言环境en_US

java - 强制 Spring 的 MBeanExporter 使用特定的 MBeanServer

java - 当套接字关闭时,是否有必要关闭从套接字的 IO 流创建的输入/输出流?

java - Python 2 和 Java 1.6 之间的 BadPaddingException AES 128 CBC

java - 未能评估断点条件。原因 : Object has been collected

json - 将结构编码为 json Go

java - 为什么 Spring Rest 服务在第一次请求时很慢?

java - 在 AWS Amazon 上自动执行 api