1. 程式人生 > >一個相對通用的JSON響應結構,其中包含兩部分:元數據與返回值

一個相對通用的JSON響應結構,其中包含兩部分:元數據與返回值

其中 als obj message true object 通過 lse string

  • 定義一個相對通用的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響應結構,其中包含兩部分:元數據與返回值