user09
user09

Reputation: 956

HttpMessageNotReadable Exceotion: JSON parse error: cannot deserialize instance of ArrayList out of start object token

I have an endpoint

@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) {}

And I am sending the request by using rest template

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

with a helper method

 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;
      }

When I look at the SO people talk about sending the object and failing as the created JSON is in wrong format but here this is a get api and I do not understand the source of the problem.

Upvotes: 0

Views: 2157

Answers (1)

user10367961
user10367961

Reputation:

This is commonly caused by a missing error handler on your RestTemplate. Your server responds with an error and your client tries to deserialize it to a List<PlacementDetail>. In order to address this, you should properly handle HTTP error codes.

See the below snippet.

@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");
        }

    }

}

Upvotes: 1

Related Questions