Reputation: 774
So, I am playing with RestTemplate in a spring-boot REST API.
I have a TEST spring-boot application which makes a restTemplate call to another application EMPLOYEE-TEST. For now I have Employee model class present in both applications but a repository present only on EMPLOYEE-TEST side.
PROBLEM: So, I'm just trying to do a normal findAll() from TEST side and in return trying to get List of Employee objects, but the problem is I get the List of LinkedHashMap objects instead of Employee object.
Now, I can set member variables one by one for small class but when class has around 10 member variables and I have thousands of such class, it isn't feasible.
Here is the code.
TestController:
@RequestMapping("/test")
public class TestController {
@Autowired
private RestTemplate restTemplate;
@Value("${rest.url}")
private String url;
@GetMapping("/")
public ResponseEntity<Object> findEmployees(){
String response = restTemplate.getForObject(this.url, String.class);
System.out.println("response is \n"+response);
List<Employee> list_response = restTemplate.getForObject(this.url, List.class);
System.out.println(list_response);
for(Object e : list_response) {
System.out.println(e.getClass());
}
return new ResponseEntity (restTemplate.getForEntity(this.url, Object[].class), HttpStatus.OK);
}
}
url = http://localhost:8080/employee/
in application.properties
EmployeeController:
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeRepository eRepository;
@GetMapping("/")
public ResponseEntity<Employee> findAll(){
return new ResponseEntity ( eRepository.findAll(), HttpStatus.OK);
}
}
Output:
response is
[{"id":1,"name":"Rahul","salary":10000},{"id":2,"name":"Rohit","salary":20000},{"id":3,"name":"Akash","salary":15000},{"id":4,"name":"Priya","salary":5000},{"id":5,"name":"Abhinav","salary":13000}]
[{id=1, name=Rahul, salary=10000}, {id=2, name=Rohit, salary=20000}, {id=3, name=Akash, salary=15000}, {id=4, name=Priya, salary=5000}, {id=5, name=Abhinav, salary=13000}]
class java.util.LinkedHashMap
class java.util.LinkedHashMap
class java.util.LinkedHashMap
class java.util.LinkedHashMap
class java.util.LinkedHashMap
So, first line in output prints response stored in string and second one is printing list_response variable.
Now, my requirement is to have List of Employee objects instead of LinkedHashMap objects.
Let me know if anything required from my end.
Upvotes: 5
Views: 7788
Reputation: 609
Use ParameterizedTypeReference
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Employee>> response = restTemplate.exchange(
"http://localhost:8080/employees/",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Employee>>(){});
List<Employee> employees = response.getBody();
https://www.baeldung.com/spring-rest-template-list
Upvotes: 4