统一返回JsonResult踩坑的记录
作者:FLGB
这篇文章主要介绍了统一返回JsonResult踩坑的记录,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
统一返回JsonResult踩坑
定义了一个统一返回类
但是没有给@Data 导致没有get/set方法,请求一直报错
public class JsonResult<T> {
private int code;
private String message;
private T data;
public JsonResult() {}
public JsonResult(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static <T> JsonResult<T> success(T data) {
return new JsonResult<>(200, "Success", data);
}
}
在使用时,JsonResult没有get/set方法时
Spring MVC 在序列化时无法将对象正确转换为 JSON,因此会被视为 视图名称,导致循环视图渲染的问题。
Completed initialization in 2 ms
GET "/api/getUser", parameters={}
Mapped to kayou.eim.controller.BasicController#users()
Using 'application/octet-stream', given [*/*] and supported [*/*]
Using @ExceptionHandler kayou.eim.controller.global.GlobalExceptionHandler#handleException(Except
Internal server error
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
Completed 406 NOT_ACCEPTABLE
"ERROR" dispatch for GET "/api/error", parameters={}
Mapped to kayou.eim.controller.global.CustomErrorController#error(HttpServletRequest)
Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, appli
Writing [{timestamp=Wed May 07 18:09:17 CST 2025, status=406, error=Not Acceptable, path=/api/getUser}]
Exiting from "ERROR" dispatch, status 406响应
{
"timestamp": 1746612557176,
"status": 406,
"error": "Not Acceptable",
"path": "/api/getUser"
}报错不够清晰准确,导致排查了一圈。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
