Spring返回json数据

第一种形式:使用注解@ResponseBody

    @RequestMapping(value = "/admin/jq", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> jq() {

        List<Map<String, Object>> allUser = (List<Map<String, Object>>) userService.getAllUsers().get("allUser");

        logger.info("allUser: " + allUser);

        return allUser;
    }

响应结果:

[
    {
        id=1,
        username=admin,
        status=true,
        roleId=1,
        description=备注描述的,
        roleName=ROLE_ADMIN
    },
    {
        id=6,
        username=adminto,
        status=true,
        roleId=2,
        description=null,
        roleName=ROLE_EXPERT
    }
]

 

第二种形式:利用HttpServletResponse结合第三方JSON组件(如Jackson、fastjson、gson)进行响应

    @RequestMapping(value = "/admin/jq2", headers = "Accept=application/json")
    public void jq2(HttpServletResponse response) throws IOException {
         response.setContentType("application/json;charset=utf-8");

         List<Map<String, Object>> allUser = (List<Map<String, Object>>) userService.getAllUsers().get("allUser");

        logger.info("allUser: " + allUser);

        String jsonString = JSON.toJSONString(allUser, SerializerFeature.WriteNullStringAsEmpty);

        logger.info("jsonString: " + jsonString);

        response.getWriter().write(jsonString);
    }

响应结果:

[
    {
        id=1,
        username=admin,
        status=true,
        roleId=1,
        description=备注描述的,
        roleName=ROLE_ADMIN
    },
    {
        id=6,
        username=adminto,
        status=true,
        roleId=2,
        description=null,
        roleName=ROLE_EXPERT
    }
]

 

posted @ 2017-05-24 12:39  vimx86  阅读(378)  评论(0编辑  收藏  举报