项目中需要访问别的项目的接口,利用其返回的数据进行操作。
记录一下如何将http中的response中的data取出使用。
RestTemplate restTemplate = new RestTemplate();
//发送请求并接收数据
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://" + ip + ":" + port + "/api/resource/v1/regions/root", generatePostJson(new HashMap<>()), String.class);
//将Rest结果转换为Map
Map<String, Object> body = JSONObject.parseObject(responseEntity.getBody());
List<Map<String, Object>> dataList = new ArrayList<>();
//接收response body
Object obj;
if(body != null) {
obj = body.get("data");
} else {
throw new Exception("请求返回空response body");
}
//将response body中的data转换为List
if(obj instanceof List<?>) {
for(Object o : (List<?>) obj) {
dataList.add(Map.class.cast(o));
}
}
//遍历List中的Map
for(Map<String, Object> data : dataList) {
logger.info("name: " + data.get("name"));
logger.info("indexCode: " + data.get("indexCode"));
logger.info("treeCode: " + data.get("treeCode"));
logger.info("parentIndexCode: " + data.get("parentIndexCode"));
}
输出结果:
name: 根节点
indexCode: aaabbbccc1111
treeCode: 1
parentIndexCode: -1
解决~