2013-07-28 104 views
5

我的代码来创建一个新的JSONObject和写入文件:toJSONString()是未定义的类型的JSONObject

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); 

我的问题是在

file.write(obj.toJSONString()); 

它说,

The method toJSONString() is undefined for the type JSONObject.

我是否缺少任何图书馆?或者我错了?有没有其他的方法来做到这一点?

+0

也许你meants'obj.toString()'? –

+0

我尝试过,但给我错误。 – MDEVLP

+0

它给出了什么错误? –

回答

8

JSONObject类没有toJSONString()方法。相反,它会覆盖toString()方法来生成json。

要获取对象的json表示形式,只需使用obj.toString()即可。

+0

但文件说另一个故事。看看http://www.json.org/javadoc/org/json/JSONObject.html#valueToString(java.lang.Object) – blackSmith

+0

@blackSmith链接已经消失。 – zionpi

+0

@zionpi:我不确定它已被移动到哪个位置。但我认为http://developer.android.com/reference/org/json/JSONObject.html应该仍然有信息。 – blackSmith

-1

我遇到同样的问题,如果你想使用toJSONString()你需要导入json-simple-1.1.jar库。

相关问题