Toriga
Toriga

Reputation: 199

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.

Upvotes: 1

Views: 3553

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19565

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.

Upvotes: 1

Related Questions