Pushpendra Jaiswal
Pushpendra Jaiswal

Reputation: 470

@JsonInclude(Include.NON_NULL) not working/ jackson serializing null values

I have placed the annotation over the class/pojo and also configured the mapper, but it still serialize null values

I am using Hibernate 4.3.7Final and Jackson 2.4.4. The collections are lazy loaded

Pojo : Removed getter and setters

@JsonInclude(Include.NON_NULL)
@Entity
@Table
public class School {

    @Id
    @GeneratedValue
    private int id;

    @OneToMany(cascade=CascadeType.ALL,fetch= FetchType.LAZY)
    private List<Student> students;

    @OneToMany(cascade=CascadeType.ALL,fetch= FetchType.LAZY)
    private List<Employee> staff;

}

JSONMapper:

@Component
public class JSONMapper extends ObjectMapper {
/**
     * 
     */
    private static final long serialVersionUID = -3131980955975958812L;

//ref http://blog.pastelstudios.com/2012/03/12/spring-3-1-hibernate-4-jackson-module-hibernate/ 

    public JSONMapper() {

        Hibernate4Module hm = new Hibernate4Module();
        registerModule(hm);
        configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        configure(SerializationFeature.INDENT_OUTPUT , false);
        configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
        setSerializationInclusion(Include.NON_NULL);  
    }
}

Output :

{"id":1,"students":null,"staff":null}

Upvotes: 9

Views: 23095

Answers (2)

StaxMan
StaxMan

Reputation: 116522

You may want to file a bug against project; it could be that handling for lazy-loaded collections (which do require special handling and overrides to default one) is not doing proper inclusion checks.

Upvotes: 3

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153850

Try using JsonInclude.NON_EMPTY instead.

Upvotes: 10

Related Questions