liuhuaqiang/src/main/java/com/example/demo/model/dto/ApiResponse.java

89 lines
2.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.example.demo.model.dto;
import java.time.LocalDateTime;
import java.util.Map;
/**
* 统一 API 响应封装。
* <p>
* 所有接口返回的统一数据格式,包含状态码、消息、时间戳和具体数据。
* </p>
*
* @param <T> 数据类型
*/
public class ApiResponse<T> {
/** 状态码200 表示成功 */
private int code;
/** 提示消息 */
private String message;
/** 返回数据 */
private T data;
/** 响应时间戳 */
private LocalDateTime timestamp;
private ApiResponse() {
this.timestamp = LocalDateTime.now();
}
/**
* 创建成功响应。
*
* @param data 数据对象
* @param <T> 数据类型
* @return 成功响应实例
*/
public static <T> ApiResponse<T> success(T data) {
ApiResponse<T> resp = new ApiResponse<>();
resp.code = 200;
resp.message = "success";
resp.data = data;
return resp;
}
/**
* 创建成功响应(自定义消息)。
*
* @param message 自定义消息
* @param data 数据对象
* @param <T> 数据类型
* @return 成功响应实例
*/
public static <T> ApiResponse<T> success(String message, T data) {
ApiResponse<T> resp = new ApiResponse<>();
resp.code = 200;
resp.message = message;
resp.data = data;
return resp;
}
/**
* 创建失败响应。
*
* @param code 错误码
* @param message 错误消息
* @param <T> 数据类型
* @return 失败响应实例
*/
public static <T> ApiResponse<T> error(int code, String message) {
ApiResponse<T> resp = new ApiResponse<>();
resp.code = code;
resp.message = message;
resp.data = null;
return resp;
}
// ---------- Getters ----------
public int getCode() { return code; }
public String getMessage() { return message; }
public T getData() { return data; }
public LocalDateTime getTimestamp() { return timestamp; }
}