【问题标题】:Filter out null fields in snakeyaml过滤掉snakeyaml中的空字段
【发布时间】:2017-02-06 07:02:51
【问题描述】:

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

【问题讨论】:

    标签: null snakeyaml


    【解决方案1】:

    经过一番研究,我终于找到了解决方案。需要更改在表示器中必须如何表示空字段 这是代码

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

    在 YAML 对象中使用这个表示器。

    【讨论】:

    • 注意:你可以像这样使用表示器:Yaml yaml = new Yaml(representer, options);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    相关资源
    最近更新 更多