You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java更新JSON数组值未同步到外部JSON文件的解决方法

根本原因

你当前的代码仅修改了JVM堆内存中存储的JSONObject属性值,没有将修改完成后的整个JSONArray数据回写到磁盘上的源JSON文件中,Java不会自动同步内存对象改动到磁盘文件,因此外部文件内容不会更新。

修复方案(基于你当前使用的json-simple库)

在内存修改逻辑执行完成后,新增写文件逻辑,将改动后的JSON数组覆盖写入原文件即可,完整代码如下:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.parser.ParseException;

public class UpdateJsonFile {
    public static void main(String[] args) throws IOException, ParseException {
        JSONParser parser = new JSONParser();
        // 注意Java字符串中反斜杠需要转义,写为双反斜杠
        String filePath = "F:\\file.json";
        JSONArray a = (JSONArray) parser.parse(new FileReader(filePath));

        for (Object o : a) {
            JSONObject person = (JSONObject) o;
            String name = (String) person.get("name");
            if (name.equalsIgnoreCase("john")) {
                String name1 = (String) person.get("name");
                System.out.println("name1" + name1);
                String city1 = (String) person.get("city");
                System.out.println("city1" + city1);
                String job1 = (String) person.get("job");
                System.out.println("job1" + job1);  
                person.put("city", "BLR");
                String city2 = (String) person.get("city");
                System.out.println("city2" + city2);
            }
        }

        // 新增:将修改后的JSONArray写回原文件
        try (FileWriter fileWriter = new FileWriter(filePath)) {
            fileWriter.write(a.toJSONString());
            fileWriter.flush();
        }
    }
}
注意事项
  • 代码使用了try-with-resources语法,会在写操作完成后自动关闭FileWriter资源,避免资源泄漏
  • 需确保项目已正确引入json-simple依赖,否则会出现类找不到报错
  • 写文件操作会直接覆盖原文件内容,操作前建议提前备份源文件避免数据丢失

内容的提问来源于stack exchange,提问作者shubham vashishth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 11:45:03