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

Discussion in 'Plugin Development' started by robertlit, Dec 2, 2019.

Thread Status:
Not open for further replies.
  1. Offline

    robertlit

    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:
    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!
     
  2. Offline

    CraftCreeper6

    @robertlit
    Does it say "An error occured while saving/creating homes to homes.json"? If so, refine your try catch to be more specific.
     
  3. Offline

    robertlit

    @CraftCreeper6
    It doesn't, it prints out the one Home object that is in the list (though doesn't save to file)

    Edit: the file is also created successfully with no errors

    Edit #2: Someone on spigot told me that I have to call FileWriter#close() after the writing and now it works!
     
    Last edited: Dec 2, 2019
Thread Status:
Not open for further replies.

Share This Page