简体   繁体   English

在JSONArray中创建JSONObject(JSON-Simple / JAVA)

[英]Create a JSONObject in a JSONArray (JSON-Simple / JAVA)

So, I'm getting a lot of troubles with adding a new JSONObject in my JSONArray. 因此,在JSONArray中添加新的JSONObject时会遇到很多麻烦。

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"): 这是我的.JSON(默认用户的所有属性都为“ 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. 首先,我创建了函数,这些函数可以毫无问题地验证用户“ admin”的属性。 So, their isn't problems when reading the JSON file, only writing on it: 因此,在读取JSON文件(仅在其上写入)时,它们并不是问题:

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; 这个“写”功能不会在我的json文件“ /usuarios.json”中进行任何更改,但是,我实际上可以毫无问题地读取我的json。 for example, this other function of my Project reads my json file to see if the password and usernames matches for the login JFrame: 例如,我项目的另一个功能读取我的json文件,以查看登录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 <3

you only changed the loaded JSON object to the memory. 您只需将加载的JSON对象更改为内存。 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上调用toString,然后序列化字符串。 JSONObject itself is not serializable. JSONObject本身不可序列化。 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);
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM