JSON Jackson 没有忽略空字段

JSON Jackson not ignoring null fields

我有一个 POJO,我正试图通过按以下方式使用 Include.NOT_EMPTY 注释来排除空字段。

已更新完整代码

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Items {

    /**
* 
*/
    @JsonProperty("items")
    private List<Item> items = new ArrayList<Item>();
    private Map<String, Object> additionalProperties =
            new HashMap<String, Object>();

    /**
     * 
     * @return
     *         The items
     */
    @JsonProperty("items")
    public List<item> getItems() {
        return items;
    }

    /**
     * 
     * @param items
     *            The items
     */
    @JsonProperty("items")
    public void setitems(List<Item> items) {
        this.items = items;
    }

    @JsonAnyGetter
    @JsonUnwrapped
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
  }

然而,当我打印出 JSON 时,我得到了以下方式的响应。

 {    "items": [
            {...}],

        "additionalProperties": { } // I expect this to be removed.
    }

知道我在这里做错了什么吗? 如果重要的话,我正在使用 Jackson-core 2.1.1。

您需要将其添加到 Class 级别 @JsonInclude(Include.NON_EMPTY)

下面这段代码对我来说工作正常

public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
    String [] characteristics = new String[]{};
    Employee emp = new Employee("John", "20", "Male", characteristics);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
    mapper.writeValue(System.out, emp);
}
class Employee {
    String name;
    String age;
    String gender;
    String [] characteristics;
    //setters and getters
    }

输出:{"name":"John","age":"20","gender":"Male"}

你能像下面这样更改你的代码,如 additionalProperties setter 和 属性 并在 class 级别使用 @JsonInclude(Include.NON_NULL)

private Map<String, Object> additionalProperties = null;

public void setAdditionalProperty(String name, Object value) {
    if(additionalProperties == null)
        additionalProperties = new HashMap<String, Object>();
    this.additionalProperties.put(name, value);
}