Here are my object mapper and yml formatter:
public static final YAMLFactory YML_FORMATTER = new YAMLFactory()
.enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)
.disable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS);
ObjectMapper mapperForYml = new ObjectMapper(YML_FORMATTER);
I write object to a file as:
try (FileOutputStream fos = new FileOutputStream("C:/Users/somepath/file.yml")) {
fos.write(mapperForYml.writeValueAsBytes(bean));
} catch (IOException e) {
throw new RuntimeException(e);
}
The bean has getters and setters added.
I added enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)
above because I don’t was quotes in my file like json.
I have a field in my pojo/bean of type String
which may have numeric value. When the value is numeric, I want that value to be written in yml file with single quotes.
Example (expected output):
group:
member:
name: John Doe
location: US
pcId: '23451'
I tried to append quotes using multiple ways like:
if (org.apache.commons.lang3.StringUtils.isNumeric(bean.getPcId())) {
me.setValue(StringUtils.quote(bean.getPcId()));
}
But doing this, I get result as '''7657658'''
in yml file (extra quotes added).
Tried traditional String
concatenation, got same result with extra quotes.
Also tried:
java.util.regex.Pattern.quote(bean.getPcId()); // result: /Q7657658/E
I cannot make field in pojo Integer
or Long
.