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

1 Answer 1

0

Based on f1sh comment's question, you can simply change the Jackson part with the JSON-P API:


import jakarta.json.Json;
import jakarta.json.JsonObject;
import java.io.StringReader;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class JsonBodyHandle implements HttpResponse.BodyHandler<JsonObject> {
    @Override
    public HttpResponse.BodySubscriber<JsonObject> apply(HttpResponse.ResponseInfo ri) {
        HttpResponse.BodySubscriber<String> upstream = HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8);
        return HttpResponse.BodySubscribers.mapping(
            upstream, body -> Json.createReader(new StringReader(body)).readObject());
        }
    }

Then you use the JsonBodyHandle:

HttpResponse<JsonObject> res = client.send(request, new JsonBodyHandle());
JsonObject json = res.body();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.