Solved JSON won't save to file (using GSON)

Discussion in 'Spigot Plugin Development' started by robertlit, Dec 2, 2019 at 6:41 PM.

  1. I am trying to save some data (a list) to a JSON file, when I print the json string out it's all fine but it won't save to the file.
    code:
    Code (Java):
    private List<Home> homes = new ArrayList<>();
        private File dataFolder = new File(getDataFolder(), "data");
        private File homesFile = new File(dataFolder, "homes.json");
        private Gson gson;

    public void onEnable() {
            gson = new Gson();
            saveDefaultConfig();
            dataFolder.mkdirs();
            try {
                homesFile.createNewFile();
            } catch (IOException e) {
                getLogger().info("An error occured while creating file homes.json");
                e.printStackTrace();
            }
        }

    public void saveJson() {
            try {
                gson.toJson(homes, new FileWriter(homesFile));
                getLogger().info(gson.toJson(homes));
            } catch (JsonIOException e) {
                getLogger().info("An error occured while saving homes to homes.json");
                e.printStackTrace();
            } catch (IOException e) {
                getLogger().info("An error occured while saving homes to homes.json");
                e.printStackTrace();
            }
        }
     
    (The list isn't empty)
    Thanks in advance!
     
    #1 robertlit, Dec 2, 2019 at 6:41 PM
    Last edited: Dec 2, 2019 at 7:03 PM
  2. Pretty sure you have to call FileWriter#close() after writing it to the file (or stick your FileWriter in a try-with-resources and it'll automatically close)
     
    • Winner Winner x 1
  3. Perfect it works! Thank you!
     
  4. Now you can use the edit title button then mark your thread as Solved ;)