gilbertpilz
gilbertpilz

Reputation: 1806

How do I stop jackson's YAML writer from quoting values

I'm working on a project to convert files from JSON to YAML. I'm using the 2.8.3 versions of the following libraries:

My YAML serialization code is extremely simple:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
ObjectWriter writer = mapper.writer();

try {
    SequenceWriter sw = writer.writeValues(System.out);
    sw.write(tree);
}
catch (IOException e) {
    e.printStackTrace();
}

The YAML produced by this code looks like the following:

serviceType: "elasticSearch"
displayName: "Elasticsearch Service"
description: "Sample Elastic Search Service"

Although it is valid YAML, I don't like the double quotes around the values. You don't need them in YAML and it makes editing the resulting file more cumbersome. Does anyone know how to configure the ObjectWriter to make jackson stop encapsulating String values in quotes?

Upvotes: 25

Views: 9338

Answers (2)

Akash Mulik
Akash Mulik

Reputation: 325

Along with minimizing quotes, you can customize your yaml by disabling or enabling features as below:

YAMLFactory ymlFormatter = new YAMLFactory()
      .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)  //removes marker characters ---
      .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)
      .disable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS)  //avoid numbers being quote
      .enable(YAMLGenerator.Feature.INDENT_ARRAYS_WITH_INDICATOR);  //list array elements by prefixing hifen

ObjectMapper mapper = new ObjectMapper(ymlFormatter);

Upvotes: 0

azurefrog
azurefrog

Reputation: 10945

There is a YAMLGenerator feature called MINIMIZE_QUOTES that will turn off the quotes.

You can enable() it when creating your YAMLFactory like so:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES));

Upvotes: 38

Related Questions