@JsonInclude(Include.NON_NULL)不工作/ jackson序列化空值

时间:2015-01-15 08:25:44

标签: java json spring hibernate jackson

我已将注释放在类/ pojo上并配置了映射器,但仍然序列化 null

我使用的是Hibernate 4.3.7Final和Jackson 2.4.4。这些集合延迟加载

Pojo:删除了getter和setter

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

输出:

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

2 个答案:

答案 0 :(得分:8)

请尝试使用JsonInclude.NON_EMPTY

答案 1 :(得分:3)

您可能想要针对项目提交错误;可能是对延迟加载的集合(需要特殊处理和覆盖默认处理)的处理没有进行适当的包含检查。