noussair
noussair

Reputation: 81

Error when executing POST request which returns a list using RestTemplate

I created a Mock service to simulate a POST request with a body like this:

{
  "DOSID": "DP02213",
  "RegionsID": "31",
  "DistrictsID": "88",
  "ApprovalDate": "09/10/2020",
  "ExpiryDate": "15/10/2020",
  "ItemsList": [
    {
      "Itemlookupcode": "1SBRJUOR00CJ3050H001",
      "Quantity": "1"
    }
  ]
}

and it has a response as below:

{
    "DeliveryDateList": [
        "2020-10-22T00:00:00+02:00",
        "2020-10-24T00:00:00+02:00"
    ]
}

The screen shot below describe the mock service:

POST RESTTEMPLATE

I created a java classes for the request and the response, then I created this java class:

public class GetProposedDateRestClient {

    private Logger logger = Logger.getLogger(getClass().getName());

    @Autowired
    public List<GetProposedDateResponseHeader> getProposedDate(GetProposedDateRequestHeader requestHeader) {


        String theUrl = "https://2760f38d-a7a0-4a9b-aee6-3cd331e0c8fc.mock.pstmn.io/GetProposedDates";

        RestTemplate restTemplate = new RestTemplate();
        List<GetProposedDateResponseHeader> result = null;

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<GetProposedDateRequestHeader> entity = new HttpEntity<GetProposedDateRequestHeader>(
                requestHeader, headers);
        try {
        ResponseEntity<List<GetProposedDateResponseHeader>> responseEntity = restTemplate.exchange(theUrl, HttpMethod.POST,
                entity, new ParameterizedTypeReference<List<GetProposedDateResponseHeader>>() {} );
        result = responseEntity.getBody();
        }
        catch(Exception e) {
            e.getMessage();
        }

        return result;
    }

}

And finally I got this error:

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
 at [Source: java.io.PushbackInputStream@29eb092b; line: 1, column: 1]

Upvotes: 0

Views: 116

Answers (2)

noussair
noussair

Reputation: 81

I was wrong about the response type, i expected a JsonArray as response type but it is a JsonObject so this code works for me :

responseEntity = restTemplate.postForObject( theUrl, requestHeader, GetProposedDateResponseHeader.class );

Upvotes: 0

Kittu
Kittu

Reputation: 198

Your response is a JsonObject and not a JsonArray. Instead of List<GetProposedDateResponseHeader> result = responseEntity.getBody();, give this a shot. GetProposedDateResponseHeader result = responseEntity.getBody();

Upvotes: 1

Related Questions