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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27959267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:42:45  来源:igfitidea点击:

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

javajsonspringhibernateHymanson

提问by Pushpendra Jaiswal

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

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

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

我正在使用 Hibernate 4.3.7Final 和 Hymanson 2.4.4。集合是延迟加载的

Pojo : Removed getter and setters

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:

JSON映射器:

@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-Hymanson-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}

回答by Vlad Mihalcea

Try using JsonInclude.NON_EMPTYinstead.

尝试改用JsonInclude.NON_EMPTY

回答by StaxMan

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.

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