AjaxJson

响应给前端的类


统一使用该类封装数据返回给前端,对于前后端分离的项目十分有用


/**
 * $.ajax后需要接受的JSON
 * 
 * @author
 * 
 */
public class AjaxJson extends HashMap<String,Object> implements Serializable {


	public AjaxJson(){
		this.put("success", true);
		this.put("code", HttpStatus.OK.value());
		this.put("msg", "操作成功");
	}

	public String getMsg() {
		return (String)this.get("msg");
	}

	public void setMsg(String msg) {//向json中添加属性,在js中访问,请调用data.msg
		this.put("msg", msg);
	}


	public boolean isSuccess() {
		return (boolean)this.get("success");
	}

	public void setSuccess(boolean success) {
		this.put("success", success);
	}
	
	@JsonIgnore//返回对象时忽略此属性
	public String getJsonStr() {//返回json字符串数组,将访问msg和key的方式统一化,都使用data.key的方式直接访问。
		// 使用 hutool 工具 json 化
		return JSONUtil.toJsonStr(this);
	}
	@JsonIgnore//返回对象时忽略此属性
	public static AjaxJson success(String msg) {
		AjaxJson j = new AjaxJson();
		j.setMsg(msg);
		return j;
	}
	@JsonIgnore//返回对象时忽略此属性
	public static AjaxJson error(String msg) {
		AjaxJson j = new AjaxJson();
		j.setSuccess(false);
		j.setMsg(msg);
		return j;
	}

	public static AjaxJson success(Map<String, Object> map) {
		AjaxJson restResponse = new AjaxJson();
		restResponse.putAll(map);
		return restResponse;
	}

	public static AjaxJson success() {
		return new AjaxJson();
	}


	@Override
	public AjaxJson put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	public AjaxJson putMap(Map m) {
		super.putAll(m);
		return this;
	}

	public int getCode() {
		return (int)this.get("code");
	}

	public void setCode(int code) {
		this.put("code", code);
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值