Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@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}
like image 393
Pushpendra Jaiswal Avatar asked Jan 15 '15 08:01

Pushpendra Jaiswal


People also ask

How do I ignore null values in Jackson?

Ignoring null fields at field level in Jackson We can do this by annotating each field with @JsonInclude(Include. NON_NULL) annotation. If a field is annotated by this, then it will be not included in the JSON output if its null.

Do not include null values in JSON response?

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL. Let's take an example to understand how we can use @JsonInclude annotation to ignore the null fields at the class level.

How do you tell Jackson to ignore a field during Deserialization if its value is null?

In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.

What is @JsonInclude in spring boot?

@JsonInclude(Include.NON_NULL) or @JsonInclude(JsonInclude.Include.NON_NULL) is used to ignore null fields in an object. In your particular example you have returned a String value that is why it is printing null.


1 Answers

Try using JsonInclude.NON_EMPTY instead.

like image 99
Vlad Mihalcea Avatar answered Sep 29 '22 23:09

Vlad Mihalcea