java后端返回Json数据格式工具类封装

package com.auth.utils;

import com.alibaba.fastjson.JSON;

/**
 * JSON数据返回类简单封装
 * @author wh445306
 * 用法:return new result(0, "成功").toString();
 */
public class result {

    private int code;         //状态码
    private String msg;       //消息
    private int  count;       //记录条数
    private Object data;      //数据对象

    /**
     * 无参构造器
     */
    public result(){
        super();
    }

    /**
     * 只返回状态码,消息
     * @param code
     * @param msg
     */
    public result(int code, String msg){
        super();
        this.code=code;
        this.msg=msg;
    }

    /**
     只返回状态码,消息,数据对象
     @param code
     @param msg
     @param data
     */
    public result(int code, String msg, Object data){
        super();
        this.code=code;
        this.msg=msg;
        this.data=data;
    }

    /**
     * 返回全部信息即:状态码,消息,记录条数,数据对象
     * @param code
     * @param msg
     * @param count
     * @param data
     */
    public result(int code, String msg, int count, Object data){
        super();
        this.code=code;
        this.msg=msg;
        this.count=count;
        this.data=data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

/*    @Override
    public String toString() {
        return "{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", count=" + count +
                ", data=" + data +
                '}';
    }*/

}

当然,上面的toString()方法也可以直接自己来处理,上面注释掉的内容。

很简易的封装,实际使用中自己可以再进行深度封装完善,这个只是一个模型。当然你高兴也可以封装成静态工具类。

posted @ 2022-10-04 00:14  IT情深  阅读(373)  评论(0)    收藏  举报