【问题标题】:JSON Jackson not ignoring null fields [duplicate]JSON杰克逊不忽略空字段[重复]
【发布时间】:2015-03-20 20:38:13
【问题描述】:

我有一个 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。

【问题讨论】:

  • 您的代码对我来说很好用。如果我创建一个new Items() 并直接对其进行序列化,则生成的 JSON 为{}
  • @JarrodRoberson 我已经检查了链接的问题,但它没有帮助。
  • 请给我们一个完整的例子。
  • 我希望您也发布用于序列化实例的代码、实际输出和您想要获得的输出。
  • 是的,我真的没有看到问题。我做了new ObjectMapper().writeValueAsString(new Items());,它产生了{}。你在哪里看到"additionalProperties": { }

标签: java json jackson


【解决方案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"}

【讨论】:

【解决方案2】:

你能改变你的代码,比如下面的附加属性设置器和属性,并在类级别使用@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);
}

【讨论】:

  • 也不行。
猜你喜欢
  • 2016-09-11
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 2022-06-22
  • 1970-01-01
  • 2020-09-28
  • 2015-12-05
  • 2016-04-19
相关资源
最近更新 更多