java返回前端实体类json数据时忽略某个属性方法

发布于:2024-06-29 ⋅ 阅读:(11) ⋅ 点赞:(0)

使用情景

日常工作里经常会碰到需要隐藏实体类的某些属性,可以减少返回值的大小,对性能可以有一定的提高,比如像create_time,update_time,is_del等等一些属性没有必要返回前端的。

使用方法

方法一

SpringBoot中忽略实体类中的某个属性不返回给前端的方法:使用Jackson的方式://第一种方式,使用@JsonIgnore注解标注在属性上。

public class HsUser  {

    private Long id;


    private Long customerId;

    private String customerName;

    private Integer status;

    @JsonIgnore
    private Integer isDel;
}

方法二

使用@JsonIgnoreProperties标注在类上,可以忽略指定集合的属性

@JsonIgnoreProperties({"isDel"})

public class HsUser  {

    private Long id;


    private Long customerId;

    private String customerName;

    private Integer status;

    private Integer isDel;
}

方法三

使用fastjson时:使用@JSONField(serialize = false)注解

public class HsUser  {

    private Long id;


    private Long customerId;

    private String customerName;

    private Integer status;

    @JSONField(serialize = false)
    private Integer isDel;
}

方法四

加上 @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) :前端就不能接收到


    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)

    private String password;

 方法五

如果是null不返回,注解:@JsonInclude(value= JsonInclude.Include.NON_NULL) 返回的字段属性为null 就不会展示给前端...可以放在类上,也可以放在字段上!

@JsonInclude(value= JsonInclude.Include.NON_NULL) 
public class HsUser  {

    private Long id;


    private Long customerId;

    private String customerName;

    private Integer status;

    private Integer isDel;
}


网站公告

今日签到

点亮在社区的每一天
去签到