spring mvc如何返回json数据

来源:互联网 发布:windows画图软件下载 编辑:程序博客网 时间:2024/05/30 23:01

springmvc如何返回json数据

常用的方法有两种:

1.利用Gson等json转换工具,将对象转换成json字符串,并通过HttpServletResponse将json字符串返回给前台

@RequestMapping("/getJson1")    public void getJson1(HttpServletResponse response)    {        HashMap map = new HashMap();        map.put("content", "hello world!");        Gson gson = new Gson();        try {            OutputStream stream = response.getOutputStream();            stream.write(gson.toJson(map).toString().getBytes());        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }

2.引入jackson包, 并指定通过@ResponseBody 直接返回对象, 这样Spring MVC会自动把对象转化成Json

    @RequestMapping("getJson2")    public @ResponseBody Map getJson2()    {        HashMap map = new HashMap();        map.put("content", "hello world!");        return map;    }   
0 0
原创粉丝点击