回傳使用JSON格式
1. 新增承載回應的類別
- 新增package com.example.demo.response
- 在該package中新增一個類別Response.java
- 依照API回應格式增加屬性
- 確保會有空的建構子
package com.example.demo.response;
public class Response {
public String code;
public String msg;
public String time;
public String datas;
public Response() {
}
}
2. 修改Controller
- 將Method回傳類型改為Response
- 將Response實例化,並設定其內容
- 在該方法的註解定義處加入produces = "application/json"
3. 查詢
3.1 Get Code
@RequestMapping(value="/api/mail/get", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody Response mailGet(){
Response res = new Response();
res.code = "0000";
res.msg = "OK";
res.time = "2017-09-01";
res.datas = "";
return res;
}
3.2 測試結果
4. 設定
4.1 Set Code
@RequestMapping(value="/api/mail/set", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody Response mailSet(){
Response res = new Response();
res.code = "0000";
res.msg = "OK";
res.time = "2017-09-01";
res.datas = "";
return res;
}
4.2 測試結果
可產生基礎JSON回應