JSONObject obj = new JSONObject(); obj.put("name", "name"); obj.put("age", 100); JSONArray list = new JSONArray(); list.add("msg 1"); list.add("msg 2"); list.add("msg 3"); obj.put("messages", list); try { try (FileWriter file = new FileWriter("test.json")) { file.write(obj.toJSONString()); file.flush(); } } catch (IOException e) { e.printStackTrace(); } System.out.print(obj); 

I get the string:

  {"name":"name","messages":["msg 1","msg 2","msg 3"],"age":100} 

And how can I enter an array of objects? To get a line of the following form:

 [{ "name": "name", "messages": ["msg 1", "msg 2", "msg 3"], "age": 100 }, { "name": "name1", "messages": ["msg 4", "msg 5", "msg 6"], "age": 101 }] 
  • Analogy Create JSONArray where to add the set obj, and then add the resulting JSONArray to the new JSONObject and work with it already - Chubatiy

1 answer 1

I think before the first object you need to create an array

 JSONArray listMain = new JSONArray(); JSONObject obj1 = new JSONObject(); obj.put("name", "name"); obj.put("age", 100); JSONArray list1 = new JSONArray(); list.add("msg 1"); list.add("msg 2"); list.add("msg 3"); obj1.put("messages", list1); listMain.add(obj1); JSONObject obj2 = new JSONObject(); obj.put("name", "name 2"); obj.put("age", 101); JSONArray list2 = new JSONArray(); list2.add("msg 4"); list2.add("msg 5"); list2.add("msg 6"); obj2.put("messages", list2); listMain.add(obj2); System.out.print(listMain); 
  • Yes, this is an option. But what if you need to add an unknown number of objects to the array? Through the cycle. That's exactly what interests. - Kamenev_D
  • one
    And what is bothering you? Well, generate your objects in a cycle, not linearly, and add to the list in the same place. What is the problem? - Chubatiy
  • one
    All thanks to all. While tried already answered. The issue is resolved. - Kamenev_D 2:53