實體轉JSON時,值為null的字段丟失問題


實體轉JSON時,值為null的字段丟失問題


  1. 有一實體類,其代碼如下:
@Data
public class StudentEntity implements Serializable {

    private static final long serialVersionUID = 2127997065197153097L;
    
    private String name;
    private String sex;
    private Integer age;
    private String phone;
}
  1. 有一Get接口,其代碼如下:
@RequestMapping("student/")
@RestController
public class StudentController {

    @GetMapping("get_student")
    public StudentEntity getStudent() {
        StudentEntity student = new StudentEntity();
        student.setName("張三");
        student.setAge(23);
        student.setSex("男");
        // 將‘電話號碼’賦值為null
        student.setPhone(null);
        return student;
    }
}
  1. 調用該接口,接收到的數據如下:
{
  "name": "張三",
  "sex": "男",
  "age": 23,
  "phone":null
}
  1. 在配置文件添加以下配置:
spring.jackson.default-property-inclusion=non_null
  1. 重啟項目,再次調用接口,接收到的數據如下:
{
  "name": "張三",
  "sex": "男",
  "age": 23
}

可以發現,值為null的’phone’並沒有被發送到前端.

  1. 移出第4步操作添加的配置,對StudentEntity實體類進行如下修改:
@Data
public class StudentEntity implements Serializable {

    private static final long serialVersionUID = 2127997065197153097L;
    
    private String name;
    private String sex;
    private Integer age;
    
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String phone;
}
  1. 重啟項目,再次調用接口,接收到的數據如下:
{
  "name": "張三",
  "sex": "男",
  "age": 23
}

總結

在Spring項目中,后端向前端發送實體數據時,剔除值為null的字段的方式可以有兩種:

  1. 修改配置文件,添加如下配置:
spring.jackson.default-property-inclusion=non_null
  1. 修改實體類,在需要的字段上添加如下注解:
@JsonInclude(JsonInclude.Include.NON_NULL)

同理,當前端從后端接收到的數據中部分鍵值對"不翼而飛",后端可以檢查是否系統是否添加了如上配置或注解.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM