jsonarray adding and overwriting

2

I am creating a game and I am in the part of creating monsters and I need a json file to save the monsters but when I create a new monsters it writes on top of what already exists as I can only add a new monster.

Code:

import org.json.*;
import java.io.*;
import java.util.*;
import java.util.Random;

public class Jsonarquivo {

public static void main(String[] args) throws IOException, JSONException {

File arq = new File("Monstros.Potato");

if(arq.exists() && !arq.isDirectory()){

JSONObject mons_data = new JSONObject();
mons_data.put("Monstro", "Lobo");
mons_data.put("Level", 2);
mons_data.put("HP", 100);

JSONArray mons_array = new JSONArray();
mons_array.put(mons_data);

JSONObject main_data = new JSONObject();
main_data.put("data", mons_array);

FileWriter fw = new FileWriter(arq);
PrintWriter fw_pw = new PrintWriter(fw);

String save = main_data.toString();

fw_pw.println(save);

fw.close();

}
else{

arq.createNewFile();

JSONObject mons_data = new JSONObject();
mons_data.put("Monstro", "Bruxa");
mons_data.put("Level", 1);
mons_data.put("HP", 1);

JSONArray mons_array = new JSONArray();
mons_array.put(mons_data);

JSONObject main_data = new JSONObject();
main_data.put("Data", mons_array);

FileWriter fw = new FileWriter(arq);
PrintWriter fw_pw = new PrintWriter(fw);

String save = main_data.toString();

fw_pw.print(save);

fw.close();

}
}
}

Output:

{"data":[{"HP":100,"Monstro":"Lobo","Level":2}]}

How do I need it to stay:

{"data":[{"HP":100,"Monstro":"Lobo","Level":2}{"HP":150,"Monstro":"Bruxa","Level":3}]}

NOTE: The game and infinity the hp and level are generated based on some accounts, and as the player adds more monsters the data of him is placed here. already tried several things but it does not work.

    
asked by anonymous 01.12.2017 / 15:32

1 answer

1

The problem is that you were not reading the file and adding the new monster to the Data element. You should change if the file exists for something like:

if(arq.exists() && !arq.isDirectory()){

    String text = new String(Files.readAllBytes(Paths.get("Monstros.Potato")), StandardCharsets.UTF_8);

    JSONObject jsonObject = new JSONObject(text);

    JSONArray mons_array = jsonObject.getJSONArray("Data");

    JSONObject mons_data = new JSONObject();
    mons_data.put("Monstro", "Lobo");
    mons_data.put("Level", 2);
    mons_data.put("HP", 100);

    mons_array.put(mons_data);

    jsonObject.put("Data", mons_array);

    FileWriter fw = new FileWriter(arq);
    PrintWriter fw_pw = new PrintWriter(fw);

    String save = jsonObject.toString();

    fw_pw.println(save);

    fw.close();

} else {
    ...
}
    
28.12.2017 / 14:15