For example, you just need to write the lines:

JSONObject outputJson = new JSONObject(); outputJson.put("id", "1"); 

We get:

 {"id":"1"} 

Write array:

 JSONArray list = new JSONArray(); list.add("auto"); outputJson.put("car",list); 

We get:

 { "car":["auto"]} 

And how to write and most importantly read this:

 { "car": [{ "id": "auto" }, { "id": "auto2" }] 

}

Ie in the array to enter an arbitrary number of objects and then count them?

    1 answer 1

    Write this:

      JSONObject outputJson = new JSONObject(); JSONArray list = new JSONArray(); //Делаем первый элемент id JSONObject id1 = new JSONObject(); id1.put("id", "auto"); //Делаем второй элемент id JSONObject id2 = new JSONObject(); id2.put("id", "auto2"); //Добавляем их в наш массив list.add(id1); list.add(id2); //Добавляем в главный outputJson.put("car", list); 

    Read this:

      String json = "{\"car\":[{\"id\":\"auto\"},{\"id\":\"auto2\"}]}"; //Преобразуем в объект JSONObject inputJson = (JSONObject) JSONValue.parse(json); //Получаем список id JSONArray ids = (JSONArray) inputJson.get("car"); 

    Well, the output elements (JSONObject) ids.get(0) , etc.

    Also the conclusion can be made through the cycle:

     for (int i = 0; i < ids.size(); i++) { System.out.println((JSONObject) ids.get(i)); } 

    The result is the following:

     Входной JSON -> {"car":[{"id":"auto"},{"id":"auto2"}]} Выходные элементы: {"id":"auto"} , {"id":"auto2"} 
    • And how to get access to a specific field? That would not be in this format as it is now displayed. If the field is not one for example, but it is necessary to consider only the specific. - Kamenev_D
    • one
      I did this: JSONArray ids = (JSONArray) person.get ("test"); for (int i = 0; i <ids.size (); i ++) {JSONObject temp = (JSONObject) ids.get (i); String D = (String) temp.get ("DDR"); String M = (String) temp.get ("Memory"); System.out.println ("1:" + D + M); @Chubatiy, thanks for the help. } - Kamenev_D