json - 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 和测试使用相同设置的多个类中。
解决方案
在进行了一些挖掘之后,我添加了以下代码以获取 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 字段名称进行了注释。一旦我解决了这个问题,事情就又开始正常工作了。
推荐阅读
- google-chrome-extension - 将相同的 Chrome 扩展程序发布到多个私有域?
- sql - 根据两个字段获取最新记录
- c++ - Cmake find_package 未检测到 Windows 中的路径
- python - 如何根据学生管理系统的用户输入在 python 中添加字典
- google-sheets - 有没有更简单的方法来说明当前日期是否在 Google 表格中的设定范围内?
- python - 通过 sqlite 查询传递变量时出现名为“ValueError:参数类型不受支持”的错误
- c# - 如何使用 netcore / net5+ 为 wpf 设置 STA 公寓状态?
- r - 即使在带有闪亮仪表板的小屏幕上,如何为dashboardSidebar 设置collapsed = FALSE?
- python - 与 pyspark 的模糊匹配
- javascript - Javascript中有没有办法让百分比(%)符号国际化?