Converting serialized JSON object back in Java

230 Views Asked by At

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.

1

There are 1 best solutions below

3
On BEST ANSWER

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();