后台给前端传json的时候,在data里想要一个list<map<>>
查找数据库得到list<String>之后,要用map使字段名和值一一对应,比如:
字段名 putPlace 值123
json格式要求:"data":[{"putPlace":"123"}]
具体操作:
1、新建listmap对象。
List<Map<String, String>> listmap = new ArrayList<>();
2、遍历list,并且new一个Map<String,String>对象map,使用map.put(,)将键值对放到map中,左边是键,右边是值。
3、将map放到listmap中,遍历结束。
for (int i = 0; i < list.size(); i++) { Map<String, String> map = new HashMap<>(); map.put("putPlace", list.get(i)); listmap.add(map); }
实例:
repository:
@Query(value = "select a.put_place \n" + "from casque as a join agent_casque_bind as b on a.id = b.casque_id and b.agent_id = ?1\n" + "group by a.put_place",nativeQuery = true) List<String> findPutPlace(String userId);
service:
/**
* 获取代理商头盔投放场所(去重)
* @param userId 代理商id
* @return 结果
*/
public List<Map<String,String>> queryPutPlace(String userId){ List<String> list = this.placeWatchCountRepository.findPutPlace(userId); List<Map<String, String>> listmap = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { Map<String, String> map = new HashMap<>(); map.put("putPlace", list.get(i)); listmap.add(map); } return listmap; }
controller:
/** * 获取代理商头盔投放场所(去重) * @param user 当前登陆用户 * @return 结果 */ @GetMapping("/placeWatch/putPlace") public Result putPlaceQuery(@CurrentUser TokenModel user){ Result result = new Result(); try{ List<Map<String, String>> list = this.placeWatchService.queryPutPlace(user.getId()); return result.success(list); }catch (Exception e){ e.printStackTrace(); return result.failure(ErrorCodeType.FIND_ERR.getMsg()); } }