How to create and append to a JSON file iteratively?

Viewed 134

My test class calls the addEachEmployeeDetailsToJSONFile method multiple times during the execution with different employee details.

The expected end result is a JSON file named mapping.json that looks like below:

EXPECTED mapping.json

[
    {
        "employee": {
            "ID": "123",
            "Name": "Gupta",
            "Department": "Accounts"
        }
    },
    {
        "employee": {
            "ID": "456",
            "Name": "Mark",
            "Department": "Marketing"
        }
    }
]

Below is my Java class.

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 JSONObject employeeDetails = new JSONObject();

protected JSONObject employeeObject = new JSONObject();

protected JSONArray employeeList = new JSONArray();

private FileWriter fileWriter;
    {
        try {
            fileWriter = new FileWriter(getMappingFile(), true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//Write to JSON file
private File getMappingFile (){
        File mappingFile = new File(getMappingFilePath);
        mappingFile.setWritable(true);
        mappingFile.setReadable(true);
        return mappingFile;
    }


public void addEachEmployeeDetailsToJSONFile(ITestContext iTestContext) {
        try {
                        //Write to first JSONObject
                        employeeDetails.put("ID", iTestContext.getId());
                        employeeDetails.put("Name", iTestContext.getName());
                        employeeDetails.put("Department", iTestContext.getDepartment());
                        

                        //Put the above JSON Object in another JSON object.
                        employeeObject.put("employees", employeeDetails);

                        
                        //Write above object to JSONArray        
                        employeeList.add(employeeObject);


                        //We can write any JSONArray or JSONObject instance to the file
                        fileWriter.append(beforeTestClassesList.toJSONString());

                    }
        catch (Exception e)
        {}
    }


    public static void main( String[] args )
    {
    addEachEmployeeDetailsToJSONFile(<pass employee Gupta instance>);
    addEachEmployeeDetailsToJSONFile(<pass employee Mark instance>);
    fileWriter.flush();
    }
}  

The JSON file is being created successfully and an entry is also being created like below, but, only the first entry of one employee details is being created and not a list of multiple employees and their details. What am I missing?

Current mapping.json file:

[
    {
        "employee": {
            "ID": "123",
            "Name": "Gupta",
            "Department": "Accounting"
        }
    }
]
1 Answers

Your code as shown only adds 1 item. So this is as expected. Also, you would create a new JSON object for each employee, not reuse the same one repeatedly. That will cause problems on subsequent saves. Further, your code is really a bit poorly architected. Due to the nature of JSON, appending to a file isn't really done. You write the entire file at once. This means you don't write until you have all the data, you don't write after adding each item to the array. The reason for this is that there's data after the element in the array to make it valid JSON, and you can't stick stuff in the middle of a file. Appending to a JSONArray in memory is fine, but when writing to disk you want to write the entire file.

Related