1.JsonResult 封装格式
public class JsonResult<T> {
private T data;
private String code;
private String msg;
public JsonResult() {
this.code = "0";
this.msg = "操作成功!";
}
public JsonResult(String code, String msg) {
this.code = code;
this.msg = msg;
}
public JsonResult(T data) {
this.data = data;
this.code = "0";
this.msg = "操作成功!";
}
public JsonResult(T data, String msg) {
this.data = data;
this.code = "0";
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2.测试controller
@RestController
@RequestMapping("/jsonresult")
public class JsonResultController {
@RequestMapping("/user")
public JsonResult<User> getUser() {
User user = new User(1, "laomi", "123456");
return new JsonResult<>(user);
}
@RequestMapping("/list")
public JsonResult<List> getUserList() {
List<User> userList = new ArrayList<>();
User user1 = new User(1, "laomi", "123456");
User user2 = new User(2, "test", "123456");
userList.add(user1);
userList.add(user2);
return new JsonResult<>(userList, "获取用户信息成功");
}
@RequestMapping("/map")
public JsonResult<Map> getMap() {
Map<String, Object> map = new HashMap<>(3);
User user = new User(1, "laomi", null);
map.put("作者信息", user);
map.put("博客地址", "http://blog.laomi.com");
map.put("CSDN地址", null);
map.put("粉丝数量", 2400);
return new JsonResult<>(map);
}
}
测试IP:http://localhost:8080/jsonresult/user
效果:
|