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