2

So, I'm getting a lot of troubles with adding a new JSONObject in my JSONArray.

My code is in Spanish, so I'll try to traduct variables&methods to English in my comments the best I can.

This is my .JSON (the default user has all the attributs as "admin"):

{"Usuarios":[{"nombre":"Admin","apellido":"Admin","direccion":"Admin","telefono":"Admin","correo":"Admin@admin.com","username":"admin","password":"admin"}]}

First, of all, I've created functions, which can verify the attributes of my user "admin" without any problem. So, their isn't problems when reading the JSON file, only writing on it:

So here is the problem, with this function:

public void agregarUsuario(String nombre, String apellido, String direccion, String telefono, String correo, String username, String password) //this function add a new user object to my array in the json
{
    try {
        JSONObject usuarios = getJSONObjectFromFile("/usuarios.json"); //Json object "usuarios"/"users" is my main json obj file
        JSONArray listaUsuario = usuarios.getJSONArray("Usuarios");     //I've start my array "Usuarios" (who is in my .json)
        JSONObject newObject = new JSONObject();                        //I created a new JSONObjectVariable, with the attributes i want in it
        newObject.put("nombre", nombre);
        newObject.put("apellido", apellido);
        newObject.put("direccion", direccion);
        newObject.put("telefono", telefono);
        newObject.put("correo", correo);
        newObject.put("username",username);
        newObject.put("password", password);
                                                                        //at this point my new object has all the attributes i want to put in my array
        listaUsuario.put(newObject);                                    //so here i tried to put in my array my new Json object
        usuarios.put("Usuarios",listaUsuario);                          //this line, is one of my attempts to figure out how to put the function working
                                                                        //it wasn't in the first time, but how listaUsuario.put(newObject) dint make any change in my .json...
                                                                        //with or without it doesn't do anything 
    }catch(JSONException e) {
        e.printStackTrace();
    }
 }

This function who "writes" does not make any changes in my json file "/usuarios.json", but, i can actually read my json without problems; for example, this other function of my Project reads my json file to see if the password and usernames matches for the login JFrame:

public boolean verificarInicioDeUsuario(String incomeUsername,String incomePassword) {
   JSONArray listaUsuario = usuarios.getJSONArray("Usuarios"); //gets in my "Usuarios"/"User" array
   for(int j=0;j<listaUsuario.length();j++) {                   //Start reading my array
        JSONObject user = listaUsuario.getJSONObject(j);        //i make a new JSONObject for use it to compare my strings
        if((user.getString("username").equals(incomeUsername))&&(user.getString("password").equals(incomePassword))) { //I compare my object username attributes with my incomeStrings
        return true;     //if the username and password matches in the same object, returns true
        }
     }
     return false; //if not, returns false
 }

Any suggestion/help? <3

Ivan Kaloyanov
  • 1,748
  • 6
  • 18
  • 24
Mamey
  • 81
  • 1
  • 10

1 Answers1

1

you only changed the loaded JSON object to the memory. you have not written it to the file. Please use below code sample and make change according to your program.

So here the main problem is : Call toString on the JSONObject, and then serialize the string. JSONObject itself is not serializable. so you have to use below:

String jsonString = jsonObject.toString();

sample code:

 public void agregarUsuario(String nombre, String apellido, String direccion, String telefono, String correo, String username, String password) //this function add a new user object to my array in the json
{
    try {
        JSONObject usuarios = getJSONObjectFromFile("/usuarios.json"); //Json object "usuarios"/"users" is my main json obj file
        JSONArray listaUsuario = usuarios.getJSONArray("Usuarios");     //I've start my array "Usuarios" (who is in my .json)
        JSONObject newObject = new JSONObject();                        //I created a new JSONObjectVariable, with the attributes i want in it
        newObject.put("nombre", nombre);
        newObject.put("apellido", apellido);
        newObject.put("direccion", direccion);
        newObject.put("telefono", telefono);
        newObject.put("correo", correo);
        newObject.put("username",username);
        newObject.put("password", password);
                                                                        //at this point my new object has all the attributes i want to put in my array
        listaUsuario.put(newObject);                                    //so here i tried to put in my array my new Json object
        usuarios.put("Usuarios",listaUsuario);                          //this line, is one of my attempts to figure out how to put the function working
                                                                        //it wasn't in the first time, but how listaUsuario.put(newObject) dint make any change in my .json...
                                                                        //with or without it doesn't do anything 

        ObjectOutputStream outputStream = null;

           outputStream = new ObjectOutputStream(new FileOutputStream("/usuarios.json"));
           System.out.println("Start Writing in to file ");
            outputStream.writeObject(usuarios.toString());
            outputStream.flush();
            outputStream.close();

    }catch(JSONException e) {
        e.printStackTrace();
    }
    catch (Exception e){
        System.err.println("Error writting json: " + e);
    }
 }
Dilanka M
  • 372
  • 1
  • 5
  • 17
  • So, its seem it works! <3 but now i have this little exception: "Error writting json: java.io.FileNotFoundException: \usuarios.json (Acceso denegado)". Could this a solution?: [link](https://stackoverflow.com/questions/19561386/java-access-is-denied-java-io-filenotfoundexception) – Mamey Jan 06 '19 at 10:01
  • please check your file permission or you can try as an above link with the absolute file path. then change it to a relative path. – Dilanka M Jan 06 '19 at 11:04
  • Okey i already done it! now I can add new objects to my JSON! thanks <3! I only have 1 more question! when I added a new person my .json got some weird symbols: [link](https://i.imgur.com/iTIavce.png) – Mamey Jan 06 '19 at 11:18
  • 1
    Try it with outputStream. writeUTF(usuarios.toString()); instead of outputStream.writeObject(usuarios.toString()); – Dilanka M Jan 06 '19 at 11:46