【发布时间】:2019-11-12 18:39:40
【问题描述】:
所以,我在 spring-boot REST API 中使用 RestTemplate。
我有一个 TEST spring-boot 应用程序,它对另一个应用程序 EMPLOYEE-TEST 进行 restTemplate 调用。 目前,我在两个应用程序中都存在 Employee 模型类,但仅在 EMPLOYEE-TEST 端存在一个存储库。
问题:所以,我只是想从 TEST 端做一个正常的 findAll() 并作为回报尝试获取 Employee 对象的列表,但问题是我得到了 LinkedHashMap 的列表对象而不是 Employee 对象。
现在,我可以为小类一一设置成员变量,但是当类有大约 10 个成员变量并且我有数千个这样的类时,这是不可行的。
这是代码。
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);
}
}
输出:
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 对象。
如果我有任何需要,请告诉我。
【问题讨论】:
标签: java json rest spring-boot objectmapper