使用SpringMVC返回JSON时,为了方便,编写了这个工具类,
可以通过连续put设置数据,方便易用。
package cn.itsub.zhuxian.utils;
import java.util.HashMap;
public class Result extends HashMap{
//禁止其他类用new创建
private Result() { }
public Result put(String key, Object value) {
super.put(key, value);
return this;
}
public static Result of(int code, String msg,Object data) {
return new Result()
.put("code", code)
.put("msg", msg)
.put("data", data);
}
public static Result of(int code, String msg) {
return new Result()
.put("code", code)
.put("msg", msg);
}
public static Result of(int code) {
return new Result().put("code", code);
}
public static Result of() {
return new Result();
}
}
下面是示例代码:
return Result.of(2, "注册成功");
也可以通过连续put添加数据:
Result.of(200)
.put("msg", "登录成功")
.put("token", "RTSKSDFIFKAFNASFLAFPAFJ")
.put("code", "12030");