gson 如何使用Java for循环创建JSON对象的JSON数组?

bpsygsoo  于 2022-11-06  发布在  Java
关注(0)|答案(3)|浏览(252)

我有一个for循环,它迭代并为不同的雇员生成键值对。
我需要创建一个如下所示的JSON数组,并在末尾将其写入一个JSON文件。
我很难找到理想的编码方式(JSON对象-〉JSON数组-〉JSON文件?)。
我愿意使用json-simple/GSON。

所需的JSON文件格式:

[
        {
            "employeeFirstName": "Mark",
            "employeeLastName": "Williams",
            "employeeDepartment": "Sales",
        },
        {
            "employeeFirstName": "John",
            "employeeLastName": "Carpenter",
            "employeeDepartment": "Accounts",
        },
        {
            "employeeFirstName": "David",
            "employeeLastName": "Hunter",
            "employeeDepartment": "Marketing",
        },
]

我尝试使用JSONObject并将其添加到JSONArray中,但是,无法确定如何为迭代编写代码。

我当前的Java类:

public class Test {

public void createEmployeesJSONArrayFile(ITestContext iTestContext) {
                for (ITestResult testResult : iTestContext.getFailedTests().getAllResults()) {
                    System.out.println("employeeFirstName: " + testResult.getEmployeeFirstName()));
                    System.out.println("employeeLastName: " + testResult.getEmployeeLastName());
                    System.out.println("employeeDepartment: " + testResult.getEmployeeDepartment());
                }
 }
}

实现这一目标的最简单或理想的方法是什么?

8wtpewkr

8wtpewkr1#

一个简单的方法是使用Gson,这是Google提供的一个API。你可以将ITestResult对象的Collection写入一个文件。toJson函数将获取ITestResult对象的集合,并将它们写入给定的Appenable对象,在本例中是指向一个文件的BufferedWriter
(未测试,1秒,不在工作站)

Collection<ITestResult> results = iTestContext.getFailedTests().getAllResults();

new GsonBuilder()
    .create()
    .toJson(results, Files.newBufferedWriter(Paths.get("path", "to", "file")));
aor9mmx1

aor9mmx12#

如果您的目标是最终写入文件,您也可以使用Jackson。

ObjectMapper mapper = new ObjectMapper();
//To add indentation to output json
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Collection<ITestResult> results = iTestContext.getFailedTests().getAllResults();
try{
  mapper.writeValue(new File("/somepath/output.json"), results);
catch (IOException){
  e.printStackTrace();
}

注意:建议使用对象Map器的单个示例

7vux5j2d

7vux5j2d3#

对于以下代码段:

public static final class Node {
    class Employee {
        private final String employeeFirstName;
        private final String employeeLastName;
        private final String employeeDepartment;

        public Employee(String employeeFirstName, String employeeLastName, String employeeDepartment) {
            this.employeeFirstName = employeeFirstName;
            this.employeeLastName = employeeLastName;
            this.employeeDepartment = employeeDepartment;
        }
    }

    List<Employee> employees = Arrays.asList(
            new Employee("Mark", "Williams", "Sales"),
            new Employee("John", "Carpenter", "Accounts"),
            new Employee("David", "Hunter", "Marketing"));

    // String json = ...
}

使用gson-utils

String json = GsonUtils.writeValue(data);

使用jackson-utils

String json = JacksonUtils.writeValue(data);

相关问题