-1

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

  • Your code looks ok. Please make sure that you re-read your `arr` object from the `"Data.JSON"` file when you start your app. You should also provide the code of `checkIfInBase` method - it seems to be missing parameter `obj2` which you're going to check if it's in your file. As for pretty-writing, please tell which Json library do you use. – Nowhere Man Apr 30 '20 at 14:45
  • I editted my question. – Maciek Groszyk Apr 30 '20 at 14:55

1 Answers1

0
  1. It is very likely that json.simple does not have feature of pretty printing, and it is quite old, so I suggest to switch to any other library. In the example below I'll be using org.json

  2. You need to re-read your json file and initialize arr variable.

  3. You may check equality of your JSON objects in the array by converting them to strings and comparing.

  4. Fix re-writing of your JSON file.

import java.io.*;
import org.json.JSONTokener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonExample {

private static JSONArray initArray(String jsonFileName) throws IOException, JSONException {
    String json = "";
    File jsonFile = new File(jsonFileName);
    if (!jsonFile.exists()) {
        return new JSONArray();
    }

    try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
        String line;
        while ((line = reader.readLine()) != null) {
            json += line;
        }
    }
    JSONTokener tokener = new JSONTokener(json);
    JSONArray readArr = new JSONArray(tokener);
    System.out.println("Read arr: " + readArr.toString());
    return readArr;
}

private static boolean isInDB(JSONObject obj, JSONArray arr) throws JSONException {
    for (int i = 0; i < arr.length(); i++) {
        JSONObject item = arr.getJSONObject(i);
        if (obj.toString().equals(item.toString())) {
            return true;
        }
    }
    return false;
}

private static JSONArray saveArray(JSONArray arr, String jsonFileName) throws JSONException, IOException {
    try (FileWriter Data = new FileWriter(jsonFileName)) {
        Data.write(arr.toString(4)); // setting spaces for indent
    }
    return arr;
}

// main method
public static void main(String[] args) throws Exception {
    JSONArray arr = initArray("DataMedicine.json");

    JSONObject obj = new JSONObject();
    obj.put("name", "Antivirin");
    obj.put("amount", 15);
    JSONObject medicine = new JSONObject();
    medicine.put("medicine3", obj);

    if (!isInDB(medicine, arr)) {
        arr.put(medicine);
        saveArray(arr, "DataMedicine.json");
    } else {
        System.out.println("Already exists in DB: " + obj);
    }
}
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • Thanks, you are amazing ;D – Maciek Groszyk Apr 30 '20 at 18:02
  • I have one more question, how can i get index of specific medicine in array list? For example i writing in text fields name of medicine which i want to delete from array. In my previous code i used remove(obj) but right now remove need index. How to get it? – Maciek Groszyk Apr 30 '20 at 19:11
  • You can reuse code of `isInDb` to return `i` when found an object, otherwise return -1. – Nowhere Man Apr 30 '20 at 20:04
  • I have one more question, how can i convert this arr to vector? I want to display my data in JTable. – Maciek Groszyk May 07 '20 at 12:29
  • Can you ask it in a new question and please provide more details. As I understand, you'll have a vector of object arrays, right? – Nowhere Man May 07 '20 at 13:05
  • Ok i deal with this, but now i got some strange error, first time i see it. Could u check my new question? https://stackoverflow.com/questions/61686042/how-to-deal-with-cannot-be-cast-to-class-error-gson-java Thank a lot :D – Maciek Groszyk May 08 '20 at 18:51