过滤掉snakeyaml中的空字段

war*_*107 5 null snakeyaml

我正在使用snakeyaml在YAML文件中打印我的对象.有些字段可能为null.当它们在文件中打印为空时,如何防止这些字段?

war*_*107 8

经过一番研究,我终于找到了解决方案.人们需要改变必须在Representer中表示空字段的方式.这是代码

Representer representer = new Representer() {
    @Override
    protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,Tag customTag) {
        // if value of property is null, ignore it.
        if (propertyValue == null) {
            return null;
        }  
        else {
            return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

在YAML对象中使用此代表.