java - 转换 JSONObject 中的缓冲阅读器 (json-simple)
问题描述
我在 GET 中调用了一个 Rest API,我需要解析响应并获取一个键的值。我在用着:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
这是我的代码:
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while ((readLine = in.readLine()) != null) {
sb.append(readLine);
}
JSONObject jsonObject = new JSONObject(sb.toString());
jsonObject.get();
in.close();
但是在JSONObject jsonObject = new JSONObject(sb.toString());
生成错误 Error:(32, 63) java: incompatible types: java.lang.String cannot be convert to java.util.Map
非常感谢。
解决方案
您应该使用JSONParser
从字符串中获取数据:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(sb.toString());
JSONObject
用于通过toJSONString()
方法将其数据序列化为 JSON 字符串。
推荐阅读
- android - 仅通过 WiFi 接口发送 POST 请求
- reactjs - 滚动视图中的图像背景不起作用 React Native
- vba - 如何创建 .vba 文件?
- dialogflow-es - Chatbase 与 Dialogflow 聊天机器人的集成,后者通过第三方 API 集成到应用程序中
- postman - 如何使用 Postman 在 BIM 360 中获取项目的图像?
- c# - C#(DotNet Core) 中用于指针的 volatile 读/写
- javascript - 为什么使用writeStream在nodejs中写入比原始文件更大的文件?
- java - JAVA - 使用 else if 从扫描仪输入进行年龄比较
- c# - 扩展方法与重载
- spring - Spring data mongodb:使用日期,日期有2小时的差异