当使用spring的webclient或webtestclient接收包含字符串列表的json主体时,我遇到了一个问题。
似乎列表没有正确解析。正文的json字符串只是放在列表的第一个条目中。
例子:
List<String> actual = this.webTestClient.get()
.uri("/path")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectBodyList(String.class)
.returnResult().getResponseBody();
我在org.springframework.web.reactive.function.client.webclientintegrationtests中尝试了一个测试:
@ParameterizedWebClientTest
void retrieveJsonArrayOfStringAsResponseEntityList(ClientHttpConnector connector) {
this.startServer(connector);
String content = "[\"Jane\", \"Jason\", \"John\"]";
this.prepareResponse(response -> response.setHeader("Content-Type", "application/json").setBody(content));
Mono<ResponseEntity<List<String>>> result = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntityList(String.class);
StepVerifier.create(result).consumeNextWith(entity -> {
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(entity.getHeaders().getContentLength()).isEqualTo(25);
assertThat(entity.getBody()).isEqualTo(Arrays.asList("Jane", "Jason", "John"));
}).expectComplete().verify(Duration.ofSeconds(3));
this.expectRequestCount(1);
this.expectRequest(request -> {
assertThat(request.getPath()).isEqualTo("/json");
assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo("application/json");
});
}
这是失败的
expected: ["Jane", "Jason", "John"]
but was : ["["Jane", "Jason", "John"]"]
以及org.springframework.test.web.reactive.server.samples.responseentitytests中的另一个失败测试:
@Test
public void entityListString() {
// @formatter:off
this.client.delete()
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBodyList(String.class)
.hasSize(3)
.contains("Jane", "Jason", "John")
// @formatter:on
;
}
...
static class PersonController {
...
@DeleteMapping
List<String> deletePersons() {
return Arrays.asList("Jane", "Jason", "John");
}
这是一个错误还是我错过了一个功能?
暂无答案!
目前还没有任何答案,快来回答吧!