Home Java去掉JSON数据中值为null的属性字段
Post
Cancel

Java去掉JSON数据中值为null的属性字段

1
@JsonInclude(JsonInclude.Include.NON_NULL) 

此方法集成于Springboot2.0中,此方法的配置意在实体类与JSON互转的时候属性值为null的不参与序列化。使用时用注解的方式:

放在标记类

1
2
3
4
5
6
7
8
@JsonInclude(JsonInclude.Include.NON_NULL) 
public class HandlePayResponse {

    private String platform_order_id;
    private String order_id;
    ...

}

属性

1
2
3
4
5
6
7
8
9
10
public class HandlePayResponse {

    ...
    @JsonInclude(JsonInclude.Include.NON_NULL) 
    private String remark1;

    private String remark2;
    ...

}

配置文件中添加全局配置

1
jackson.default-property-inclusion:non_null

不过这配置要慎用,不然你项目中所有的实体类转为JSON需要显示时,值为null的都不会显示。

使用前效果:{"platform_order_id":"20191025112603731","order_id":"12345","merchant_id":"1","sign":"3b8944f68fd2a3ef54dc349cba207e457435bd653375d10043adec832d9db14c","sign_type":"SHA256","total_amount":"1","remark1":null,"remark2":null,"qrUrl":"https://qr.chinaums.com/bills/qrCode.do?id=30471910253040324116767159","code":"SUCCESS","errorMassage":null}

使用后效果:{"platform_order_id":"20191025104352324","order_id":"12345","merchant_id":"1","sign":"388db8c52c86b4843f676340fb12c10ee1ca2674eeb4057dd0cb58d00adc0e17","sign_type":"SHA256","total_amount":"1","qrUrl":"https://qr.chinaums.com/bills/qrCode.do?id=30471910256385241102482750","code":"SUCCESS"}

参考:Java取掉json数据中值为null的属性字段

This post is licensed under CC BY 4.0 by the author.