проблема REST-ответ с Spring ResponseEntity <Integer>с JDK 11 - PullRequest
2 голосов
/ 28 февраля 2020

Я выполняю миграцию JDK8 на JDK11, поэтому я обновляю springboot до 2.2.4.RELEASE + и добавляю:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Я компилирую в java 8.

Контроллер:

    @RequestMapping(value = "/{model}/nbLines", method = RequestMethod.GET, consumes = MediaType.ALL_VALUE, produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<Integer> getNbLines(@PathVariable String model) {
        LOGGER.info("getNbLines : model[{}]", model);
        Integer nbLines = modelService.getNbLines(model);
        return Optional.ofNullable(nbLines).map(result -> new ResponseEntity<>(result, HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.NO_CONTENT));
    }

My JSON curl:

$ curl -s --header "Принять: application / json" http://localhost: 8084 / noraui / api / hello / nbLines

8

My XML curl:

$ curl -s --header "Принять: application / xml" http://localhost : 8084 / noraui / api / hello / nbLines

<Integer>8</Integer>

Мой модульный тест (ОК с JDK8 , но не с JDK11 ):

@Test
public void getHelloNbLines() {
    ResponseEntity<Integer> entity = new RestTemplate().getForEntity("http://localhost:" + port + "/noraui/api/hello/nbLines", Integer.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(entity.getBody()).isEqualTo(8);
}

Я пытаюсь с:

@Test
public void getHelloNbLines() {
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Content-Type", "application/json");
    ResponseEntity<Integer> entity = new RestTemplate().exchange("http://localhost:" + port + "/noraui/api/hello/nbLines", HttpMethod.GET, new HttpEntity<Object>(headers), Integer.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(entity.getBody()).isEqualTo(8);
}

Моя ошибка:

[ERROR] getHelloNbLines(com.github.noraui.datas.web.services.rest.NoraUiDatasControllerTests)  Time elapsed: 0.135 s  <<< FAILURE!
org.springframework.web.client.RestClientException:
Error while extracting response for type [class java.lang.Integer] and content type [application/xml]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.lang.Integer` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.Integer` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 1]

Ответы [ 3 ]

1 голос
/ 28 февраля 2020

Accept заголовок теперь обязательный :

"Accept: application/json

@Test
public void getHelloNbLines() {
    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Accept", "application/json");
    ResponseEntity<Integer> entity = new RestTemplate().exchange("http://localhost:" + port + "/noraui/api/hello/nbLines", HttpMethod.GET, new HttpEntity<Object>(headers), Integer.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(entity.getBody()).isEqualTo(8);
}
0 голосов
/ 28 февраля 2020

Попробуйте добавить эту зависимость -

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.5.1</version>
</dependency>
0 голосов
/ 28 февраля 2020

Попробуйте добавить -Djava.locale.providers=COMPAT в качестве параметров виртуальной машины и посмотрите, пройдет ли она.

Вы также можете напечатать тело объекта, чтобы увидеть, что на самом деле принимается.

...