Springboot之返回json数据格式的两种方式-yellowcong

SpringBoot返回字符串的方式也是有两种,一种是通过@ResponseBody@RequestMapping(value = "/request/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") 中的produces = "application/json;charset=UTF-8" 来设定返回的数据类型是json,utf-8编码,第二种方式,是通过response的方式,直接写到客户端对象。在Springboot中,推荐使用注解的方式。

代码地址

https://gitee.com/yellowcong/springboot-demo/tree/master/springboot-json

目录结构

JSONController2 这个类,是这个案例的代码,JSONController 是上一篇的例子。
Springboot之返回json数据格式的两种方式-yellowcong_第1张图片

1、通过@ResponseBody

通过@ResponseBody 方式,需要在@RequestMapping 中,添加produces = "application/json;charset=UTF-8",设定返回值的类型。

/**
 * 创建日期:2018年4月6日
* 代码创建:黄聪
* 功能描述:通过request的方式来获取到json数据
* @param jsonobject 这个是阿里的 fastjson对象 * @return */
@ResponseBody @RequestMapping(value = "/body/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") public String writeByBody(@RequestBody JSONObject jsonParam) { // 直接将json信息打印出来 System.out.println(jsonParam.toJSONString()); // 将获取的json数据封装一层,然后在给返回 JSONObject result = new JSONObject(); result.put("msg", "ok"); result.put("method", "@ResponseBody"); result.put("data", jsonParam); return result.toJSONString(); }

2、通过HttpServletResponse来返回

通过HttpServletResponse 获取到输出流后,写出数据到客户端,也就是网页了。

/**
 * 创建日期:2018年4月6日
* 代码创建:黄聪
* 功能描述:通过HttpServletResponse 写json到客户端
* @param request * @return */
@RequestMapping(value = "/resp/data", method = RequestMethod.POST) public void writeByResp(@RequestBody JSONObject jsonParam,HttpServletResponse resp) { // 将获取的json数据封装一层,然后在给返回 JSONObject result = new JSONObject(); result.put("msg", "ok"); result.put("method", "HttpServletResponse"); result.put("data", jsonParam); //写json数据到客户端 this.writeJson(resp, result); } /** * 创建日期:2018年4月6日
* 代码创建:黄聪
* 功能描述:写数据到浏览器上
* @param resp * @param json */
public void writeJson(HttpServletResponse resp ,JSONObject json ){ PrintWriter out = null; try { //设定类容为json的格式 resp.setContentType("application/json;charset=UTF-8"); out = resp.getWriter(); //写到客户端 out.write(json.toJSONString()); out.flush(); } catch (IOException e) { e.printStackTrace(); }finally{ if(out != null){ out.close(); } } }

3、测试

可以看到,我先访问的是HttpServletResponse的这个类,然后才是通过Springmvc提供的方法反回,可以看到,编码都是utf-8,也是json的数据类型。
Springboot之返回json数据格式的两种方式-yellowcong_第2张图片

参考文章

https://www.cnblogs.com/yoyotl/p/7026566.html

你可能感兴趣的:(springboot)