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?
In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.
Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!!
In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.
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);
}
}
};
Use this representer in YAML object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With