如何使用Java 11 HttpClient和Jackson将JSON响应映射到Java类?仅适用于 Java 11 的解决方案HttpClient::sendAsync适用于 Java 11 和HttpClient::sendHttpClient::sendAsync

我是Java 11 HttpClient的新手,想试一试。我有一个简单的GET请求返回JSON,我想将JSON响应映射到一个名为的Java类。Questionnaire

我知道我可以将响应开箱即用地转换为字符串或输入流,如下所示

HttpRequest request = HttpRequest.newBuilder(new URI(String.format("%s%s", this.baseURI, "/state")))
          .header(ACCEPT, APPLICATION_JSON)
          .PUT(noBody()).build();

HttpResponse<String> response = this.client.send(request, HttpResponse.BodyHandlers.ofString());

如何编写将 JSON 字符串转换为我的问卷类的内容,如下所示?

HttpResponse<Questionnaire> response = this.client.send(request, HttpResponse.BodyHandlers./* what can I do here? */);

我使用 Jackson 将 JSON 转换为 Java 类实例。Jackson 是否支持新的 Java 标准 HttpClient?

更新 1我不够精确,很抱歉。我正在寻找一个阻塞获取示例。我知道 http://openjdk.java.net/groups/net/httpclient/recipes.html#jsonGet


答案 1

仅适用于 Java 11 的解决方案HttpClient::sendAsync

基于此链接,您可以执行如下操作:

public static void main(String[] args) throws IOException, URISyntaxException, ExecutionException, InterruptedException {
        UncheckedObjectMapper uncheckedObjectMapper = new UncheckedObjectMapper();

        HttpRequest request = HttpRequest.newBuilder(new URI("https://jsonplaceholder.typicode.com/todos/1"))
                .header("Accept", "application/json")
                .build();

        Model model = HttpClient.newHttpClient()
                .sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .thenApply(uncheckedObjectMapper::readValue)
                .get();

        System.out.println(model);

}

class UncheckedObjectMapper extends com.fasterxml.jackson.databind.ObjectMapper {
        /**
         * Parses the given JSON string into a Map.
         */
        Model readValue(String content) {
            try {
                return this.readValue(content, new TypeReference<Model>() {
                });
            } catch (IOException ioe) {
                throw new CompletionException(ioe);
            }
        }

}

class Model {
        private String userId;
        private String id;
        private String title;
        private boolean completed;


    //getters setters constructors toString
}

我使用了一些虚拟终结点,它提供示例 JSON 输入和示例模型类,以使用 Jackson 将响应直接映射到类。Model

适用于 Java 11 和HttpClient::sendHttpClient::sendAsync

我通过定义自定义找到了一种方法:HttpResponse.BodyHandler

public class JsonBodyHandler<W> implements HttpResponse.BodyHandler<W> {

    private Class<W> wClass;

    public JsonBodyHandler(Class<W> wClass) {
        this.wClass = wClass;
    }

    @Override
    public HttpResponse.BodySubscriber<W> apply(HttpResponse.ResponseInfo responseInfo) {
        return asJSON(wClass);
    }

    public static <T> HttpResponse.BodySubscriber<T> asJSON(Class<T> targetType) {
        HttpResponse.BodySubscriber<String> upstream = HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8);

        return HttpResponse.BodySubscribers.mapping(
                upstream,
                (String body) -> {
                    try {
                        ObjectMapper objectMapper = new ObjectMapper();
                        return objectMapper.readValue(body, targetType);
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                });
    }
}

然后我称之为:

public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {

    HttpRequest request = HttpRequest.newBuilder(new URI("https://jsonplaceholder.typicode.com/todos/1"))
                .header("Accept", "application/json")
                .build();

    Model model = HttpClient.newHttpClient()
                .send(request, new JsonBodyHandler<>(Model.class))
                .body();

    System.out.println(model);

}

响应是:

Model{userId='1', id='1', title='delectus aut autem', completed=false}

的 JavaDoc 对于解决这个问题特别有用。可以进一步改进它以使用而不是定义 .HttpResponse.BodySubscribers::mappingHttpResponse.BodySubscribers::ofInputStreamHttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8)BodySubscriberJsonBodyHandler


答案 2

简化 Java 11 @michalk解决方案 HttpClient::send

HttpService 类示例:

public class HttpService {

private final HttpClient httpClient= HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();

public HttpService() {}

public <T> T sendGetRequest(String url, Class<T> responseType) throws IOException, InterruptedException {
    HttpRequest request = HttpRequest.newBuilder().GET().uri(URI.create(url)).header("Accept", "application/json").build();

    HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

    return new ObjectMapper().readValue(response.body(), responseType);
}

public <T> List<T> sendGetListRequest(String url, Class<T> responseType) throws IOException, InterruptedException {

    HttpRequest request = HttpRequest.newBuilder().GET().uri(URI.create(url)).header("Accept", "application/json").build();

    HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(response.body(), objectMapper.getTypeFactory().constructCollectionType(List.class, responseType));
}}

模型类示例:

public class Model {

private String id;

public Model() {}

public String getId() { return this.id; }

public void setId(String id) { this.id = id; }

@Override
public String toString() { return "Model{" + "id='" + id + '\'' + '}'; }}

发送 HTTP GET 请求:

public class Main {

public static void main(String[] args) {
    try {
        HttpService httpService = new HttpService();

        Model model = httpService.sendGetRequest("http://localhost:8080/api/v1/models/1", Model.class);
        System.out.println("Single Object:" + model);

        System.out.print('\n');

        List<Model> models = httpService.sendGetListRequest("http://localhost:8080/api/v1/models", Model.class);
        for(Model m: models) { System.out.println("Object:" + m); }

    }
    catch (IOException | InterruptedException e) {
        System.err.println("Failed to send GET request: " + e.getMessage());
    }
}}

响应:

Single Object: Model{id='1'}

Object: Model{id='1'}
Object: Model{id='2'}
Object: Model{id='3'}

必需的 Maven 依赖项 (pom.xml):

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.10.3</version>
    </dependency>

推荐