首页 > 解决方案 > 转换 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

非常感谢。

标签: javajsonparsingjson-simplerest

解决方案


您应该使用JSONParser从字符串中获取数据:

JSONParser parser = new JSONParser(); 
JSONObject json = (JSONObject) parser.parse(sb.toString());

JSONObject用于通过toJSONString()方法将其数据序列化为 JSON 字符串。


推荐阅读