A relatively generic JSON response structure with two parts: metadata and return value

  • Define a relatively general JSON response structure, which contains two parts: metadata and return value. The metadata indicates whether the operation is successful and the return value message, etc. The return value corresponds to the data returned by the server method.
public class Response {

    private static final String OK = "ok";
    private static final String ERROR = "error";

    private Meta meta;
    private Object data;

    public Response success() {
        this.meta = new Meta(true, OK);
        return this;
    }

    public Response success(Object data) {
        this.meta = new Meta(true, OK);
        this.data = data;
        return this;
    }

    public Response failure() {
        this.meta = new Meta(false, ERROR);
        return this;
    }

    public Response failure(String message) {
        this.meta = new Meta(false, message);
        return this;
    }

    public Meta getMeta() {
        return meta;
    }

    public Object getData() {
        return data;
    }

    public class Meta {

        private boolean success;
        private String message;

        public Meta(boolean success) {
            this.success = success;
        }

        public Meta(boolean success, String message) {
            this.success = success;
            this.message = message;
        }

        public boolean isSuccess() {
            return success;
        }

        public String getMessage() {
            return message;
        }
    }
}

 

The above Response class includes two types of general return value messages: ok and error, and also includes two commonly used operation methods: success( ) and failure( ). An inner class is used to display the metadata structure, which we will use many times below. Response class.

  • The JSON response is structured as follows:
{
    "meta": {
        "success": true,
        "message": "ok"
    },
    "data": ...
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325038150&siteId=291194637