所以,我在 spring-boot REST API 中使用 RestTemplate。
我有一个 TEST spring-boot 应用程序,它对另一个应用程序 EMPLOYEE-TEST 进行 restTemplate 调用。
现在,我在两个应用程序中都存在 Employee 模型类,但仅在 EMPLOYEE-TEST 端存在一个存储库。
问题:所以,我只是想从 TEST 端做一个普通的 findAll() 并作为返回尝试获取 Employee 对象列表,但问题是我得到的是 LinkedHashMap 对象列表而不是 Employee 对象。
现在,我可以为小类一个一个地设置成员变量,但是当类有大约 10 个成员变量并且我有数千个这样的类时,这是不可行的。
这是代码。
测试 Controller :
@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/
在 application.properties
员工 Controller :
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeRepository eRepository;
@GetMapping("/")
public ResponseEntity<Employee> findAll(){
return new ResponseEntity ( eRepository.findAll(), HttpStatus.OK);
}
}
输出:
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
因此,输出中的第一行打印存储在字符串中的响应,第二行打印 list_response 变量。
现在,我的要求是拥有 Employee 对象列表而不是 LinkedHashMap 对象。
如果我需要什么,请告诉我。
最佳答案
使用 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
关于java - 将 GET 响应从 restTemplate 转换为自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56846975/