I am using snakeyaml to print my object in a YAML file. There are some fields which could be null. How can I prevent these field, when they are null from being printed in the file?
Asked
Active
Viewed 5,010 times
1 Answers
18
After some research I have finally found the solution. One needs to change how null fields have to be represented in Representer Here is the code
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);
}
}
};
String s = new Yaml(representer).dump(obj)

Pavel Vlasov
- 4,206
- 6
- 41
- 54

warrior107
- 709
- 1
- 9
- 25
-
Note: you can use the representer like this: `Yaml yaml = new Yaml(representer, options);` – Csuki Apr 03 '19 at 08:28