You need to enable JavaScript to run this app. 如何迭代创建并追加内容到JSON文件?Java实现仅输出单条员工数据排查
优惠活动
大模型
产品
解决方案
定价
更多

如何迭代创建并追加内容到JSON文件?Java实现仅输出单条员工数据排查

问题原因&解决方案

你代码里存在以下几个核心错误:

  • 成员变量复用导致数据覆盖:employeeDetails、employeeObject是类的成员变量,每次调用addEachEmployeeDetailsToJSONFile方法时,都是修改同一个对象的值,JSONArray存储的是对象引用,所以最终数组里所有元素都会是最后一次赋值的内容
  • 变量名错误:
    • getMappingFile方法中使用了未定义的getMappingFilePath变量,你实际定义的路径变量是filePath
    • 写文件时调用的beforeTestClassesList不存在,你实际定义的数组变量是employeeList
  • Key值不匹配:你往employeeObject里put的键是employees(复数),但你期望的输出键是employee(单数)
  • 写入时机错误:每次调用方法就执行写入操作,会导致多次拼接JSON字符串,生成不合法的JSON结构,应该等所有员工数据都添加到数组后,一次性写入文件
  • 方法调用错误:addEachEmployeeDetailsToJSONFile是实例方法,静态的main方法不能直接调用,需要先创建Test类的实例
  • 空catch块吞掉异常:所有运行错误都被空catch捕获,你无法感知代码运行时的报错信息

修正后代码

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import java.io.*;

public class Test {
    private String filePath = new File("").getAbsolutePath() + File.separator + "target" + File.separator + "mapping.json";
    // 仅将存储所有员工的数组保留为成员变量
    protected JSONArray employeeList = new JSONArray();
    private FileWriter fileWriter;

    public Test() {
        try {
            fileWriter = new FileWriter(getMappingFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private File getMappingFile (){
        // 修正路径变量名错误
        File mappingFile = new File(filePath);
        mappingFile.setWritable(true);
        mappingFile.setReadable(true);
        return mappingFile;
    }


    public void addEachEmployeeDetailsToJSONFile(ITestContext iTestContext) {
        try {
            // 每次调用方法都创建新的局部对象,避免复用导致数据覆盖
            JSONObject employeeDetails = new JSONObject();
            employeeDetails.put("ID", iTestContext.getId());
            employeeDetails.put("Name", iTestContext.getName());
            employeeDetails.put("Department", iTestContext.getDepartment());
            
            JSONObject employeeObject = new JSONObject();
            // 修正key为单数,和期望输出一致
            employeeObject.put("employee", employeeDetails);
            employeeList.add(employeeObject);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 所有数据添加完成后再统一写入文件
    public void writeAllDataToFile() {
        try {
            fileWriter.write(employeeList.toJSONString());
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main( String[] args ) {
        // 先创建类实例再调用实例方法
        Test test = new Test();
        test.addEachEmployeeDetailsToJSONFile(<pass employee Gupta instance>);
        test.addEachEmployeeDetailsToJSONFile(<pass employee Mark instance>);
        test.writeAllDataToFile();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 19:00:05