swagger返回结果字段显示问题总结

2,425 阅读2分钟

这是我参与更文挑战的第1天,活动详情查看: 更文挑战


swagger页面,设置不显示值为null的返回实体属性

尝试1:类上面添加注解@JsonInclude,无效

import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.ALWAYS)

尝试2:注解设置@ApiModelProperty(hidden=false),无效

@ApiModelProperty(hidden=false)
private Long workTimeFloor;

原因:ResultVo包装了一层实体,ResultVo有对属性的设置

@ApiModelProperty(value="内容",required=true)
private T content;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Map;

@Data
@ApiModel(value="ResVo",description="通用返回类型")
public class ResVo<T> {

    @ApiModelProperty(value="状态码",required=true)
    private Integer status;
    @ApiModelProperty(value="消息",required=true)
    private Object message;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty(value="内容",required=true)
    private T content;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty(value="统计",required=true)
    private Map<String,Object> statistics;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @ApiModelProperty(value="分页",required=true)
    private TPageVo tPageVo;
    @ApiModelProperty(value="token",required=true)
    private String token;
}

swagger隐藏某些字段(有值无值都隐藏)

尝试1:属性上面添加注解@JsonIgnore,无效

import com.fasterxml.jackson.annotation.JsonInclude;
@JsonIgnore
private Long workTimeFloor;

无效原因:

@JsonIgnore 是Jackson 的注解,spring boot 发往客户端的数据默认是用jackson 序列化

如果用alibaba 的 fastJson将注解改为@JSONField(serialize = false),JSONField是来自com.alibaba.fastjson.annotation包的

尝试2:注解设置@ApiModelProperty(hidden=true),无效

@ApiModelProperty(hidden=true)
private Long workTimeFloor;

通过原因上面的无效原因,添加@JSONField(serialize = false),生效

@JSONField(serialize = false)
private Long workTimeFloor;

对@JsonIgnore的理解

@JsonIgnore的作用是,在json序列化时,将java bean中的一些属性忽略掉,可以使用在属性或方法上,产生的效果就是当响应某个user对象时,就不会把该字段响应出去;但是会有一个问题,这样一来,当使用@RequestBody接收json格式的对象时,会把对应字段也忽略掉

@JsonIgnore注解注释

Annotation only needs to be added to one of the accessors (often
 * getter method, but may be setter, field or creator parameter),
 * if the complete removal of the property is desired.
 * However: if only particular accessor is to be ignored (for example,
 * when ignoring one of potentially conflicting setter methods),
 * this can be done by annotating other not-to-be-ignored accessors
 * with {@link JsonProperty} (or its equivalents). This is considered
 * so-called "split property" case and allows definitions of
 * "read-only" (read from input into POJO) and "write-only" (write
 * in output but ignore on output)

参考:

spring boot @JsonIgnore 失效的问题

使用@JsonIgnore遇到的坑