簡體   English   中英

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

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

因此,在JSONArray中添加新的JSONObject時會遇到很多麻煩。

我的代碼是西班牙語,所以我會盡力將注釋中的變量和方法翻譯成英文。

這是我的.JSON(默認用戶的所有屬性都為“ admin”):

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

首先,我創建了函數,這些函數可以毫無問題地驗證用戶“ admin”的屬性。 因此,在讀取JSON文件(僅在其上寫入)時,它們並不是問題:

所以這是這個功能的問題:

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();
    }
 }

這個“寫”功能不會在我的json文件“ /usuarios.json”中進行任何更改,但是,我實際上可以毫無問題地讀取我的json。 例如,我項目的另一個功能讀取我的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
 }

有什么建議/幫助嗎? <3

您只需將加載的JSON對象更改為內存。 您尚未將其寫入文件。 請使用以下代碼示例,並根據您的程序進行更改。

因此,這里的主要問題是:在JSONObject上調用toString,然后序列化字符串。 JSONObject本身不可序列化。 所以你必須在下面使用:

String jsonString = jsonObject.toString();

樣例代碼:

 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