0
点赞
收藏
分享

微信扫一扫

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

RockYoungTalk 2022-04-26 阅读 73
java后端

代码地址

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

目录结构

JSONController2 这个类,是这个案例的代码,JSONController 是上一篇的例子。
这里写图片描述

1、通过@ResponseBody

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

/**
 * 创建日期:2018年4月6日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:通过request的方式来获取到json数据<br/>
 * @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日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:通过HttpServletResponse 写json到客户端<br/>
 * @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日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:写数据到浏览器上<br/>
 * @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的数据类型。
这里写图片描述

参考文章

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

举报

相关推荐

0 条评论