对于JSONObject类型,未定义java – 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.

我错过了任何图书馆吗?或者我错了吗?有替代方法吗?

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

要获取对象的json表示,只需使用obj.toString().

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...