Day07-JsonResult

98 阅读1分钟

调整JsonResult

当服务器端需要向客户端响应数据时,在JsonResult类中,必须添加新的属性,以表示“响应到客户端的数据”,例如:

@Data
public class JsonResult implements Serializable {

    private Integer state;
    private String message;
    // 以下是新增的
    private Object data;
 
    // 暂不关心其它代码
}

并且,可以新增ok()方法,在原有的ok()方法的基础上进行重载,例如:

public static JsonResult ok() {
    // JsonResult jsonResult = new JsonResult();
    // jsonResult.state = ServiceCode.OK.getValue();
    // return jsonResult;
    return ok(null);
}

public static JsonResult ok(Object data) {
    JsonResult jsonResult = new JsonResult();
    jsonResult.state = ServiceCode.OK.getValue();
    jsonResult.data = data;
    return jsonResult;
}

然后,在处理需要响应数据的请求中,通过新的带参数的ok()方法进行响应,例如:

@GetMapping("")
public JsonResult list() {
    log.debug("开始处理【查询相册列表】的请求,无参数");
    List<AlbumListItemVO> list = albumService.list();
    return JsonResult.ok(list);
}

其实,更推荐将data属性的类型通过泛型来声明,例如:

private T data;

当类中的属性的类型为泛型时,在类上也需要声明,例如:

public class JsonResult<T> implements Serializable {
    // ...
}

并且,在静态方法上,如果使用了泛型,还需要单独声明,例如:

public static <T> JsonResult<T> ok(T data) {
    // ...
}

当使用涉及泛型的方法和类型时,如果你不关心泛型的实际使用类型,则应该通过Void类型来表示,例如:

public static JsonResult<Void> fail(ServiceCode serviceCode, String message) {
    JsonResult<Void> jsonResult = new JsonResult<>();
    jsonResult.state = serviceCode.getValue();
    jsonResult.message = message;
    return jsonResult;
}