-2

I have a POJO and Im trying to exclude null fields by using the Include.NOT_EMPTY annotation in the following manner.

Updated with Complete code

@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);
    }
  }

However,when I print out the JSON, I get a response in the following manner.

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

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

Any idea what Im doing wrong here? I'm using Jackson-core 2.1.1 if that matters.

seeker
  • 6,841
  • 24
  • 64
  • 100

2 Answers2

3

You need to add it on the Class level @JsonInclude(Include.NON_EMPTY)

The following piece of code works fine for me

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
    }

Output : {"name":"John","age":"20","gender":"Male"}

shikjohari
  • 2,278
  • 11
  • 23
  • 1
    @KodeSeeker Use @JsonInclude(Include.NON_NULL) instead of @JsonInclude(JsonInclude.Include.NON_EMPTY) – Vivek Jan 22 '15 at 06:19
  • @VVK. NON_NULL is a subset of NON_EMPTY http://jackson.codehaus.org/1.9.9/javadoc/org/codehaus/jackson/map/annotate/JsonSerialize.Inclusion.html#NON_EMPTY – seeker Jan 22 '15 at 06:37
  • @KodeSeeker yep...I used `NON_EMPTY` because I had an empty array – shikjohari Jan 22 '15 at 06:41
0

Can you change your code like additionalProperties setter and property as below and use @JsonInclude(Include.NON_NULL) at class level

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);
}
Naveen Ramawat
  • 1,425
  • 1
  • 15
  • 27