英文:
Convert Buffered Reader in 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());
这一行会生成一个错误
错误:(32, 63) java: 不兼容的类型:java.lang.String无法转换为java.util.Map
非常感谢。
英文:
i'm calling a Rest API in GET, and i need to parse the response and take the value of a key.
I'm using:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
This is my code:
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();
But in JSONObject jsonObject = new JSONObject(sb.toString());
generate a error
Error:(32, 63) java: incompatible types: java.lang.String cannot be converted to java.util.Map
Thanks so much.
答案1
得分: 1
你应该使用 JSONParser
从字符串中获取数据:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(sb.toString());
JSONObject
通过 toJSONString()
方法将其数据序列化为 JSON 字符串。
英文:
You should be using JSONParser
to get the data from String:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(sb.toString());
JSONObject
is used to serialize its data into JSON string via toJSONString()
method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论