1

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.

Toriga
  • 189
  • 2
  • 7
  • 17

1 Answers1

1

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.

Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • Thanks so much. If now i want take the value, how do, i tried json.get('key1') but nothing, the structure is like this {status:200 data:{key1:value,key2:value}}, i want get key1:value. Thanks so much – Toriga May 04 '20 at 19:21
  • You need to get `data` object first, and then get `key1` out of it: `String v1 = ((JSONObject)simpleJson.get("data")).get("key1").toString();` – Nowhere Man May 04 '20 at 19:26
  • 1
    I did in this way and work ... `JSONObject json = (JSONObject) parser.parse(sb.toString()); JSONObject jsonData = (JSONObject) json.get("data"); String stringTranslated = (String) jsonData.get("translation");` – Toriga May 05 '20 at 08:23
  • `JSONParser` is deprecated. – Bigeyes Mar 15 '23 at 17:43
  • It's Gson's `JsonParser` that is [deprecated](https://stackoverflow.com/questions/60771386/). Initial question was tagged and related to another Json Library [`json-simple`](https://code.google.com/archive/p/json-simple/) which has been godforsaken for a long time. [v.1.1.1 JavaDoc](https://javadoc.io/doc/com.googlecode.json-simple/json-simple/latest/index.html) does not mention deprecation. – Nowhere Man Mar 15 '23 at 18:32
  • However, it appears this project was forked and continued at Clifton Labs, [maven repo](https://mvnrepository.com/artifact/com.github.cliftonlabs/json-simple), where [JSONParser](https://jar-download.com/artifacts/com.github.cliftonlabs/json-simple/2.3.0/source-code/org/json/simple/parser/JSONParser.java) got deprecated -- but this is definitely another story. – Nowhere Man Mar 15 '23 at 18:48