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?
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().
I meet the same question, if you want to use toJSONString() you need to import json-simple-1.1.jar library.
The method toJSONString() is from json-simple but I guess you are using org.json.
org.json have an alternative to toJSONString().
You can simply use: obj.toString(1).
The difference to the toString() method is, that if you pass "1" as parameter org.json automatically will format and beautify your JSON.
So you don't have only one single compressed line of JSON in your file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With