Result.java

  1. import com.fasterxml.jackson.annotation.JsonInclude;
  2. import lombok.*;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. @Data
  6. @ToString
  7. @Builder
  8. @AllArgsConstructor
  9. public class Result<T> {
  10. /** 返回码 */
  11. private String code;
  12. /** 返回消息 */
  13. private String message;
  14. /** 数据时间 */
  15. private Long time;
  16. /** 返回数据 */
  17. @JsonInclude(JsonInclude.Include.NON_NULL)
  18. private T data;
  19. public Result(){
  20. time=System.currentTimeMillis();
  21. }
  22. public Result message(String message){
  23. this.setMessage(message);
  24. return this;
  25. }
  26. public Result code(String code){
  27. this.setCode(code);
  28. return this;
  29. }
  30. public Result code(ResultCode resultCode){
  31. this.setCode(resultCode.getCode());
  32. this.setMessage(resultCode.getMessage());
  33. return this;
  34. }
  35. public Result data(String key, Object value){
  36. this.setData((T)new HashMap<>(1).put(key,value));
  37. return this;
  38. }
  39. public Result data(Map<String, Object> map){
  40. this.setData((T)map);
  41. return this;
  42. }
  43. public Result data(Object value)
  44. {
  45. this.setData((T)value);
  46. return this;
  47. }
  48. }

ResultCode.java

  1. import lombok.Data;
  2. import lombok.Getter;
  3. /**
  4. * 返回码类
  5. */
  6. @Getter
  7. public enum ResultCode {
  8. SUCCESS("200", "ok"),
  9. ERROR("500", "error"),
  10. FORBIDDEN("403", "请求失败"),
  11. UNAUTHORIZED("401", "认证失败"),
  12. TOKEN_EXPIRED("901", "请求失败");
  13. /**
  14. * 错误类型码
  15. */
  16. private String code;
  17. /**
  18. * 错误类型描述信息
  19. */
  20. private String message;
  21. ResultCode(String code, String message) {
  22. this.code = code;
  23. this.message = message;
  24. }
  25. }