如何编写展示数据的restful接口
接收数据库数据
通过MyBatis或者JPA获取到的数据可以用List<Map<String, Object>>来接收
例如
List<Map<String, Object>> allPerson =personService.findALLPersonAccount();
这样在遍历时处理数据就会很方便
处理举例:
//参数中的list为已经获取到的数据库数据
private JSONArray getPersonJsonArray(List<Map<String, Object>> list){
JSONArray jsonArray = new JSONArray()
for (Map result: list){
JSONObject jsonObject = new JSONObject();
jsonObject.put("ID",result.get("ID"));
if(result.get(DATE")!=null){
jsonObject.put("Date",result.get(DATE").toString().substring(0,19));
}else{
jsonObject.put("Date",null);
jsonArray.add(jsonObject);
}
return jsonArray;
}
将数据在↑方法中处理过后,如下展示:
@RequestMapping(value = "/getPersonAll",method = RequestMethod.POST)
public ResponseEntity<?> getPersonAll(HttpServletResponse response) throws IOException {
List<Map<String,Object>> person = personService.findALLPersonAccount();
Map<String, Object> map = new HashMap<String, Object>();
map.put("data", getPersonJsonArray(person));
map.put("status", HttpStatus.OK.value());
map.put("message", "查询所有人员信息成功!");
// JSONObject object = new JSONObject();
// object.toJSONString(person);
// object.put("ID",person.get(0));
// response.getWriter().print(object.toJSONString(person));
return new ResponseEntity(map, HttpStatus.OK);
}
输出结果:
{
"data": [
{
"cardID": 1,
"openDate": "2020-10-28 10:30:33",
}
],
"message": "查询所有人员信息成功!",
"status": 200
}