首页 > 解决方案 > 在响应 json 文件中排除数据成员

问题描述

我的 Json 响应文件中出现了不需要的数据字段。我尝试使用@JsonIgnore,但仍然在输出中得到不需要的字段。以下是模型类:

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Data
@JsonInclude(Include.NON_NULL)
public class RToleranceResponse implements Serializable  {
    
    //This object is used to check if the object is empty or not (all data members are null)
    @JsonIgnore
    private static final RToleranceResponse EMPTY = new RToleranceResponse();
    
    private static final long serialVersionUID = -8284498145392258180L;
    private String description;
    private Double totalMean;
    private Double Rmrisk;
    private Double upsideHm;

    
    // Function to check if the current object is empty
    public boolean isEmpty() {
        return this.equals(EMPTY);
    }

}

Postman 上的 Json 输出:

"tolerance": {
      "description": "Very conservative",
      "empty": false
}

不希望这个 EMPTY 变量存在。其中 EMPTY 变量用于检查整个对象是否为空(因为我使用的是 new 关键字)。这只是一个示例类和输出,以保持问题很小。那么如何从响应 Json 文件中排除数据字段。

标签: javajsonspring-bootrest

解决方案


empty在 JSON 响应中来自publicmethod isEmpty()。将 也添加@JsonIgnore到该公共方法以将其从 JSON 响应中删除。


推荐阅读