You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hexo-theme-yorha-test/source/_posts/spring-boot-response-keng.md

2.7 KiB

title: 关于Spring里类的私有字段的一些坑 author: lensfrex cover: 'https://oss-img.ciduid.top/blog/covers/cover(10).jpg' tags:

  • Java
  • 笔记 categories: [] date: 2022-07-11 15:42:00

封面:https://www.pixiv.net/artworks/98234187


话先说在前头:

记得写上getter/setter方法


我们写统一响应类一般会这么写:

package net.lensfrex.dscape.domain.response;

public class Response<T> {
    private final int code;
    private final String message;
    private final T data;

    public Response(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static<T> Response<T> success(T data) {
        return new Response<>(20000, "success", data);
    }

    public static Response<Object> error(int code, String message) {
        return new Response<>(code, message, null);
    }
}

在controller里边如果是这样写:

@RestController
@RequestMapping("/user")
public class User {

    @PostMapping(value = "/login" , produces = "application/json")
    public Response<LoginResponseData> result(@RequestBody String body) {
        LoginResponseData loginResponseData = new LoginResponseData();
        loginResponseData.setRole(0);
        loginResponseData.setUid("uuid");
        loginResponseData.setAccessToken("token");
        loginResponseData.setExpired(120202002);
        loginResponseData.setRefreshToken("refreshToken");


        return Response.success(loginResponseData);
    }
}

当我们发起请求的时候,会出现这样的问题:

{
    "timestamp": "2022-07-11T07:49:09.656+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "path": "/user/login"
}

程序会打出这样的日志:

2022-07-11 15:49:09.652 WARN 14728 --- [tp1298557761-40] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class net.lensfrex.dscape.domain.response.Response] with preset Content-Type 'null']

也就是说没法把这个类给转换成json

这是因为在Spring MVC里面将实体Bean转换成json时,是通过对应字段的getter来获取到其值的。我们这里并没有为其提供相应的getter方法,所以没法获取到字段的值,因为所有字段都是private,所以得到的也都是null,也就没法转成json,产生错误。

因此在编写统一返回类的时候应当要注意带上getter方法。

番外:

如果想让值为null的字段不参与序列化,则在这个类标注上@JsonInclude(JsonInclude.Include.NON_NULL),这样,在json输出的时候,这个null字段就会消失,在json中不会有这个key