Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toJSONString() is undefined for the type JSONObject

Tags:

java

json

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?

like image 940
MDEVLP Avatar asked Jul 28 '13 11:07

MDEVLP


3 Answers

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().

like image 86
Bohemian Avatar answered Nov 06 '22 08:11

Bohemian


I meet the same question, if you want to use toJSONString() you need to import json-simple-1.1.jar library.

like image 42
user7219682 Avatar answered Nov 06 '22 08:11

user7219682


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.

like image 1
Max Avatar answered Nov 06 '22 08:11

Max