1. 程式人生 > >Springboot之返回json資料格式的兩種方式-yellowcong

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 是上一篇的例子。
這裡寫圖片描述

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的資料型別。
這裡寫圖片描述

參考文章