Response JSON
大部份的API都會回傳json 本文介紹一些回傳json的方式
Controller
@Controller
public class HelloworldController {
@RequestMapping(value = "/returnJson", method = RequestMethod.GET)
@ResponseBody
public String returnJson(HttpServletRequest request) throws JSONException {
JSONObject ret = new JSONObject();
ret.put("hello", "json");
return ret.toString();
}
@RequestMapping(value = "/returnModel.json", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public User returnModel(HttpServletRequest request) throws JSONException {
User user = new User(1, "welson");
return user; // auto convert to json
}
}
class User {
int id;
String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
說明
- 一般mvc的框架在執行完controller後都會進入view的頁面,但如果只想單純回傳資料,請宣告
@ResponseBody
- 本例介紹兩種回傳json的方式:
- (1)
@Responsebody
為String
- (2)只要是key/value形式的Class,可以自動回傳json資料。(如本例的
User
)
- (1)