toJSONString() is undefined for the type JSONObject
java, json
Solution
The JSONObject class doesn't have a `toJSONString()` method. Instead it overrides the `toString()` method to generate json.
To get the json representation of the object, simply use `obj.toString()`.
Problem
My code to create a new JSONObject and write to a file: ``` JSONObject obj = new JSONObject(); obj.put("name", "abcd"); obj.put("age", new Integer(100)); JSONArray list = new JSONArray(); list.add("msg 1"); list.add("msg 2"); list.add("msg 3"); obj.put("messages", list); try { FileWriter file = new FileWriter("c:\\test.json"); file.write(obj.toJSONString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } System.out.print(obj); ``` My problem is at ``` file.write(obj.toJSONString()); ``` It says that The method toJSONString() is undefined for the type JSONObject. Am I missing any library? Or am I going about it wrong? Is there alternative way to do it?