0

I'm writting an Java application that do requests through REST API to Named Entity Recognition service (deeppavlov) running in a local network.

So I request data by following:

        String text = "Welcome to Moscow, John";
        List<String> textList = new ArrayList<String>();
        textList.add(text);
        JSONObject json = new JSONObject();
        json.put("x", textList);

        String URL = "http://localhost:5005/model";
        HttpClient client = HttpClient.newBuilder()
            .version(Version.HTTP_1_1)
            .build();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(URL))
            .header("accept", "application/json")
            .header("Content-Type", "application/json")
            .POST(BodyPublishers.ofString(json.toString()))
            .build();

        try {

            HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
            System.out.println(response.body());
            System.out.println(response.body().getClass());

        } catch (IOException | InterruptedException e) {
           
        }

As result I get:

[[["Welcome","to","Moscow",",","John"],["O","O","B-GPE","O","B-PERSON"]]] class java.lang.String

It is a string and I don't know how to convert it to object, array, map or list to iterate through. Please help.

user164863
  • 580
  • 1
  • 12
  • 29

1 Answers1

1

It depends from the library that you are using to deserialize the string. It seems that you are using org json code, so a possible solution uses a JSONTokener:

Parses a JSON (RFC 4627) encoded string into the corresponding object

and then use the method nextValue:

Returns the next value from the input. Can be a JSONObject, JSONArray, String, Boolean, Integer, Long, Double or JSONObject#NULL.

The code will be the following

Object jsonObject = new JSONTokener(jsonAsString).nextValue();
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • Is it `import org.json.JSONTokener;`? I get `cannot find symbol [ERROR] symbol: class JSONTokener [ERROR] location: package org.json` – user164863 Aug 09 '21 at 18:24
  • Yes for android. Otherwise you need to adapt using a backend library – Davide Lorenzo MARINO Aug 10 '21 at 04:42
  • Ok @Davide , I have found it now: `import org.json.simple.parser.ParseException; import org.json.simple.parser.JSONParser; JSONParser parser = new JSONParser(); Object obj = parser.parse(text);`. Thank you for the tip! – user164863 Aug 10 '21 at 14:03