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}
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.
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.
In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.
@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.
Try using JsonInclude.NON_EMPTY instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With