1

I want to fetch a jakarta.json.JsonObject in the HttpResponse itself using the Jakarta JSONP API. Right now, I have to fetch it as a String, feed the body into a reader and then get the JsonObject like the code below.

import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import jakarta.json.Json;
import jakarta.json.JsonObject;
import jakarta.json.JsonReader;

HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
JsonReader jsonReader = Json.createReader(new StringReader(response.body()));
JsonObject object = jsonReader.readObject();
jsonReader.close();

How do I get the response as HttpResponse<JsonObject> response directly? I don't want to use any external libraries other than the Jakarta JSONP one.

Edit: As an example, one could write their own BodyHandler like this:

import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodySubscriber;
import java.net.http.HttpResponse.BodySubscribers;
import java.net.http.HttpResponse.ResponseInfo;

import jakarta.json.JsonObject;

public class JsonObjectBodyHandler implements HttpResponse.BodyHandler<JsonObject> {

    @Override
    public BodySubscriber<JsonObject> apply(ResponseInfo responseInfo) {
        // How to implement this
    }

}

and then use it in the function like this:

HttpResponse<JsonObject> response = httpClient.send(request, new JsonObjectBodyHandler());
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
khateeb
  • 5,265
  • 15
  • 58
  • 114
  • 1
    Does this answer your question? [Deserializing JSON using Java 11 HttpClient and custom BodyHandler with Jackson halts and will not proceed](https://stackoverflow.com/questions/57629401/deserializing-json-using-java-11-httpclient-and-custom-bodyhandler-with-jackson) – f1sh Feb 14 '23 at 15:06
  • @f1sh That doesn't answer the question because it uses Jackson to serialize JSON Response bodies to POJOs and I want to simply convert the body to a JsonObject without any external library. – khateeb Feb 15 '23 at 07:31

0 Answers0