首页 > 解决方案 > Spring WebClient 不处理 JSON 内容

问题描述

我有一个使用 WebClient 从 ComicVine 获取 JSON 数据的应用程序,如下所示:

WebClient client = WebClient.builder()
  .baseUrl(url)
  .defaultHeaders(
    headers -> {
      headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
      headers.add(HttpHeaders.USER_AGENT, "ComiXed/0.7");
    })
  .build();

Mono<ComicVineIssuesQueryResponse> request =
  client
    .get()
    .uri(url)
    .accept(MediaType.APPLICATION_JSON)
    .retrieve()
    .bodyToMono(ComicVineIssuesQueryResponse.class);

ComicVineIssuesQueryResponse response = request.block();

有一段时间,这奏效了。但是,突然之间,它在执行时抛出了以下根异常:

Caused by: org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/json' not supported for bodyType=org.comixed.scrapers.comicvine.model.ComicVineIssuesQueryResponse
    at org.springframework.web.reactive.function.BodyExtractors.lambda$readWithMessageReaders$12(BodyExtractors.java:201)

我不确定为什么它突然不会处理 JSON 数据。我的单元测试,显式返回 JSON 数据并正确设置内容类型:

private MockWebServer comicVineServer;

this.comicVineServer.enqueue(
  new MockResponse()
    .setBody(TEST_GOOD_BODY)
    .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE));

任何想法为什么会这样?它发生在对 WebClient 和测试使用相同设置的多个类中。

标签: jsonspringwebclient

解决方案


在进行了一些挖掘之后,我添加了以下代码以获取 JSON 作为字符串,然后使用 ObjectMapper 将其转换为目标类型:

Mono<String> request =
  client
    .get()
    .uri(url)
    .accept(MediaType.APPLICATION_JSON)
    .retrieve()
    .bodyToMono(String.class);

String value = request.block();
ObjectMapper mapper = new ObjectMapper();
ComicVineIssuesQueryResponse response = mapper.readValue(value, ComicVineIssuesQueryResponse.class);

这很快暴露了潜在的问题,即响应中的两个实例变量使用相同的 JSON 字段名称进行了注释。一旦我解决了这个问题,事情就又开始正常工作了。


推荐阅读