HttpMessageNotReadable例外:JSON解析错误:无法从起始对象令牌中反序列化ArrayList的实例

时间:2018-10-19 01:54:50

标签: java json rest jackson spring-rest

我有一个端点

@GetMapping(value = "/accounts/{accountId}/placementInfo", headers = "version=1")
  @ResponseStatus(HttpStatus.OK)
  public List<PlacementDetail> findPlacementDetailByPlacementInfoAtTime(@PathVariable("accountId") Long accountId,
                                                                        @RequestParam(value = "searchDate", required = false)
                                                                        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate searchDate) {}

我正在使用rest模板发送请求

placementResponseEntity = restTemplate.exchange(placementUriBuilder(accountId, searchDate), HttpMethod.GET,
          apiRequestEntity,new ParameterizedTypeReference<List<PlacementDetail>>() {});

使用辅助方法

 private String placementUriBuilder(long accountId, LocalDate searchDate) throws IOException {
        String resourceUri = ACCOUNT_RESOURCE_URI_START + accountId + PLACEMENT_DETAIL_RESOURCE_URI_END;
        String url;

        if(searchDate != null) {
          url = UriComponentsBuilder.fromUri(serverUri.getUri()).path(resourceUri).queryParam("searchDate", searchDate.format(DateTimeFormatter.ISO_DATE)).build().toUriString();
        } else {
          url = UriComponentsBuilder.fromUri(serverUri.getUri()).path(resourceUri).build().toUriString();
        }
        return url;
      }

当我查看SO时,人们谈论发送对象并失败,因为创建的JSON格式错误,但这是一个get api,我不明白问题的根源。

1 个答案:

答案 0 :(得分:1)

这通常是由RestTemplate上缺少错误处理程序引起的。您的服务器响应错误,客户端尝试将其反序列化为List<PlacementDetail>。为了解决这个问题,您应该正确处理HTTP错误代码。

请参见下面的代码段。

@Configuration
public class ClientConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder
                .errorHandler(new ClientErrorHandler())
                .build();
    }


    public class ClientErrorHandler implements ResponseErrorHandler {

        @Override
        public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
            // check if HTTP status signals an error response
            return !HttpStatus.OK.equals(httpResponse.getStatusCode());
        }

        @Override
        public void handleError(ClientHttpResponse httpResponse) throws IOException {
            // handle exception case as you see fit
            throw new RuntimeException("Error while making request");
        }

    }

}