jsonarray adding and overwriting

Asked

Viewed 144 times

2

I’m creating a game and I’m in the monster part and I need a json file to save the monsters but when I create a new monster it writes on top of what already exists as I arrange to just 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();

}
}
}

Exit:

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

How I need you to stay:

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

NOTE: the game and infinity hp and level are generated based on a few accounts, and Form the player add more monsters their data be placed here. I’ve tried a lot of things.

1 answer

1


The problem is that you were not reading the file and adding the new monster to the widget Date. You should change if when the file exists to 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 {
    ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.