码迷,mamicode.com
首页 > Web开发 > 详细

一个相对通用的JSON响应结构,其中包含两部分:元数据与返回值

时间:2018-04-29 22:39:12      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:col   数据   get   相对   return   static   操作方法   success   结构   

  • 定义一个相对通用的JSON响应结构,其中包含两部分:元数据与返回值,其中,元数据表示操作是否成功与返回值消息等,返回值对应服务端方法所返回的数据。
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;
        }
    }
}

 

以上Response类包括两类通用返回值消息:ok与error,还包括两个常用的操作方法:success( )与failure( ),通过一个内部类来展现元数据结构,我们在下文中多次会使用该Response类。

  • 该JSON响应结构如下:
{
    "meta": {
        "success": true,
        "message": "ok"
    },
    "data": ...
}

 

一个相对通用的JSON响应结构,其中包含两部分:元数据与返回值

标签:col   数据   get   相对   return   static   操作方法   success   结构   

原文地址:https://www.cnblogs.com/gengaixue/p/8972132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!