使用JOVA在一个JSON文件中添加多个包含单个字符串的JSON对象,使用Java

发布于 2025-02-01 10:58:11 字数 3237 浏览 1 评论 0 原文

我正在研究一个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 single json对象(只有一个filewriter迭代,正确的语法


两个 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验证器 添加了两个filewriter

结果在Json和Java;有关下面的任何其他查询评论。

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:

This is the Image of the JSON File containing a Single JSON Object (only one FileWriter iteration, CORRECT Syntax)

Two FileWriter Iterations output below:

This is the Image of the contents of the JSON File containing Multiple JSON Objects containing a single Array of Strings Each, (two 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 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文