未定义类型JSONObject的toJSONString() [英] toJSONString() is undefined for the type JSONObject

查看:442
本文介绍了未定义类型JSONObject的toJSONString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码以创建一个新的JSONObject并写入文件:

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

我的问题在

file.write(obj.toJSONString());

JSONObject类型的toJSONString()方法未定义.

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?

推荐答案

JSONObject 类没有toJSONString()方法.而是将 toString() 方法覆盖为生成json.

The JSONObject class doesn't have a toJSONString() method. Instead it overrides the toString() method to generate json.

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

To get the json representation of the object, simply use obj.toString().

这篇关于未定义类型JSONObject的toJSONString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆