Home > OS >  RestTemplate postForEntity return List of DTO
RestTemplate postForEntity return List of DTO

Time:05-18

im working ina spring project and using restemplate to call POST API that take a List of DTOOne And return a List of DTOTWO.

this is my code :

  List<MYDTOONE> listDTORequest;
  //values..
  
  ResponseEntity<List<MYDTOOTWO>> userActionsResponse = restTemplate.postForEntity("my yrl",
    listDTORequest, MYDTOOTWO.class);

im geeting a Syntax error in the last param i need to know how i can tell postForEntity that im waiting for List.

i tried also List<MYDTOOTWO> in the last paramater but still syntax error

thanks in advance.

CodePudding user response:

It may not be the cleanest code, but it is the fastest and simplest way I have found to do it. You read it as an Array and then put it in the List.

List<MYDTOONE> listDTORequest;

// JDK8
List<MYDTOOTWO> userActionsResponse = Arrays.asList(restTemplate.postForEntity("my url", listDTORequest, MYDTOOTWO[].class).getBody());

// JDK9 
List<MYDTOOTWO> userActionsResponse = List.of(restTemplate.postForEntity("my url", listDTORequest, MYDTOOTWO[].class).getBody());

CodePudding user response:

You can try to use the following new ParameterizedTypeReference<List< MyDtoTwo>>() {} instead of MYDTOOTWO.class (MyDtoTwo written for ease of reading) with the exchange method (UPDATE: postForEntity has parameterizedTypeReference removed).

What happens in your case is the response you get back is parsed as MYDTOOTWO.class however you're trying to interpret the result as a list, resulting in a mismatch. With parameterized type reference, you can specify that you're expecting a list of MYDTOOTWO.class instead.

Your call should be:

ResponseEntity<List<MYDTOOTWO>> userActionsResponse = exchange("my yrl", HttpMethod.POST,
    listDTORequest, new ParameterizedTypeReference<List< MYDTOOTWO>>() {});

List<MYDTOTWO> body = userActionsResponse.getBody();
  • Related