【发布时间】:2017-02-06 07:02:51
【问题描述】:
我正在使用snakeyaml 在 YAML 文件中打印我的对象。有些字段可能为空。 当它们为空时,如何防止这些字段在文件中打印?
【问题讨论】:
我正在使用snakeyaml 在 YAML 文件中打印我的对象。有些字段可能为空。 当它们为空时,如何防止这些字段在文件中打印?
【问题讨论】:
经过一番研究,我终于找到了解决方案。需要更改在表示器中必须如何表示空字段 这是代码
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);