简体   繁体   中英

Convert Buffered Reader in JSONObject (json-simple)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM