spring boot 返回的json中去掉值为null的属性

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29726869/article/details/81745764

 

spring boot 返回的json中去掉值为null的属性

spring boot会自动将返回的对象实例自动转化为json格式,如果对象中含空值的时候,json就会出现value值为null的情况,前端则会显示出null. 
共有两种办法可以解决

1.将null值转化为空字符串

2.将去掉值为null的属性

只需要在返回的对象上加一个注解(@JsonSerialize)就可以解决问题 
eg:


import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class AccountList {
    private String userName;
    private String realName;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getRealName() {
        return realName;
    }
    public void setRealName(String realName) {
        this.realName = realName;
    }

}

spring boot 使用 json 响应时去除 null 的字段

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

public class RespObject implements Serializable {

    private static final long serialVersionUID = -1560603887556641494L;

    ....

    @JsonInclude(Include.NON_NULL)
    public Object respMsg;

    @JsonInclude(Include.NON_NULL)
    public Object respData;

    ....

}

猜你喜欢

转载自blog.csdn.net/qq_29726869/article/details/81745764