I'm working on a Java Project that involves a GUI using FXML and I'm currently stuck on the I/O part of the project which involves writing Arrays containing Strings to a single JSON File, I have used the JSON-Simple Maven Dependency from Google.
This is what I have currently done so far for the File Writing part:
@SuppressWarnings("unchecked")
@FXML
public void submitCardio(ActionEvent event) throws IOException, ParseException {
//set file variable with file path
File file = new File(cardioFileName);
//get text field user input from GUI
String nameField = cardioNameField.getText();
//get text field user input from GUI
String durationField = cardioDurationField.getText();
//declare and initialise Array
String[] cardioArr = new String[2];
//define array indexes
cardioArr[0] = nameField;
cardioArr[1] = durationField;
//declare JSON Object
JSONObject jsonObject = new JSONObject();
//declare JSON Array
JSONArray jsonArray = new JSONArray();
//iterate over indexes of String array and adding strings to JSON array
for (int i = 0; i < 2; i++) {
jsonArray.add(cardioArr[i]);
}
// Creating JSON Object with cardio key and containing the JSON Array
jsonObject.put("cardio", jsonArray);
/**
* Try block which includes the code that appends to File (FileWriter)
*/
try(BufferedWriter bw = new BufferedWriter(new FileWriter(cardioFileName, true))){
String jsonString = jsonObject.toJSONString();
bw.append(jsonString);
bw.newLine();
bw.flush();
bw.close();
} catch(IOException e) {
e.printStackTrace();
}
final String addFile = "/MainMenu.fxml";
final Parent root = FXMLLoader.load(getClass().getResource(addFile));
Scene scene = new Scene(root);
Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
stage.setScene(scene);
stage.setTitle("Main Menu");
stage.setResizable(false);
stage.show();
}
I have tried writing to the JSON File however there are Syntax errors once I have added more than a single JSON Object.
Single FileWriter Iteration output below:
Two FileWriter Iterations output below:
I'd like to be able to add Multiple JSON Objects without resulting in wrong syntax in the JSON File, as of now Single iteration of writing to file works correctly, however multiple attempts to write JSON Object to file result in Syntax errors, included below:
JSON Validator Results of Multiple JSON Objects added upon Two Iterations of FileWriter
Any help will be appreciated, I'm still new at JSON and Java; for any further queries comment below.