使用JOVA在一个JSON文件中添加多个包含单个字符串的JSON对象,使用Java
我正在研究一个Java项目,该项目涉及使用FXML的GUI,目前我陷入了该项目的I/O一部分,该项目涉及编写包含字符串的单个JSON文件的编写数组,我有使用了Google的JSON-SIMPLE MAVEN依赖性。
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.
单 fileWriter迭代输出下面:
这是包含a
两个 filewriter迭代在下面输出:
这是包含多个JSON对象的JSON文件内容的图像FileWriter iterations, WRONG Syntax)
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文件正常工作,但是,多次尝试编写JSON对象以文件语法错误, 包括:
结果在Json和Java;有关下面的任何其他查询评论。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论