我创建一个新的 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()
。
关于java - toJSONString() 未为 JSONObject 类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17907812/