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 }]