【问题标题】:Spring WebClient not processing JSON contentSpring WebClient 不处理 JSON 内容
【发布时间】:2020-11-04 23:25:56
【问题描述】:

我有一个使用 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 和测试的多个类中。

【问题讨论】:

    标签: json spring webclient


    【解决方案1】:

    在做了一些挖掘之后,我添加了以下代码来获取 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 字段名称进行了注释。一旦我解决了这个问题,事情又开始正常工作了。

    【讨论】:

      【解决方案2】:

      您可以将json内容解析为字符串,而无需调用block方法。

      选项 1) Jackson2Tokenizer

      选项 2) 将调用“objectMapper.readValue(..) ..”的代码放入地图运算符

      【讨论】:

        猜你喜欢
        • 2018-08-18
        • 2019-02-20
        • 2020-08-02
        • 2021-08-06
        • 2021-01-04
        • 2019-12-04
        • 2020-06-03
        • 2021-08-13
        • 1970-01-01
        相关资源
        最近更新 更多