I am stuck with saving data in json file from text fields. This code below working pretty good, but after restart my app and try to add new obj2, previous data is deleting. I tried to use append, but then it was saving out of [] in json file. My second problem is prettyWriting my data in json file, i cannot implement this method in my code dont know why. If u have some idea how to solve it i would be grateful.
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
obj1.put("name", tfNameOfMedicine.getText());
obj1.put("amount",tfAmountOfMedicine.getText());
obj2.put("Medicine", obj1);
if(!checkIfInBase()) {
arr.add(obj2);
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(arr.toJSONString());
Data.flush();
JOptionPane.showMessageDialog(null, "Saved!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error");
}
}else{JOptionPane.showMessageDialog(null, "This medicine exist in data base");}
tfAmountOfMedicine.setText("");
tfNameOfMedicine.setText("");
}
According to Alex Rudenko comment: 1.I dont know if i re-read arr, i creating it like this below private declaration.
JSONArray arr = new JSONArray();
2.This is my check method.
private boolean checkIfInBase() {
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
int size = arr.size();
obj1.put("name", createMedicine().getName());
obj1.put("amount", createMedicine().getAmount());
obj2.put("Medicine", obj1);
boolean a = false;
for (int i = 0; i < size; i++) {
if (obj1.equals(arr.get(i))) {
a = true;
break;
}
}
return a;
}
3. i am using json.simple