groovyyamlgroovy-3.0yamlbuilder

Write a literal YAML field using Groovy 3.0's new YamlBuilder


Groovy 3.0 has a new YamlBuilder class that works in a similar way to the existing JsonBuilder class.

I'm trying to work out if I can use YamlBuilder to generate a literal field in YAML such as:

data: |
  this is
  a literal
  text value

My first guess was Groovy's multiline string would work:

new YamlBuilder() {
  data: '''\
this is
a literal
text value'''
}

But that gives me:

data: "this is\na literal\ntext value\n"`

I don't see anything useful in the YamlBuilder Javadoc and mrhaki's example doesn't show this use-case.

Does anyone know if/how this can be done?


Solution

  • You can do the following:

    import groovy.yaml.*
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
    import static com.fasterxml.jackson.dataformat.yaml.YAMLGenerator.Feature.LITERAL_BLOCK_STYLE
    
    def yaml = new YamlBuilder()
    
    yaml {
      data '''\
    this is
    a literal
    text value'''
    }
    
    println new ObjectMapper(new YAMLFactory().configure(LITERAL_BLOCK_STYLE, true)).writeValueAsString(yaml)
    

    If you need your own custom serialization