Search code examples
javajacksonjackson-databind

Jackson YAML Serialization - Prevent Multiline Writing


I'm trying to create a YAML file from beans. In which one of the fields has more than 80 chars. When I write the bean to YAML file using objectMapper, those values were printed in two different lines.

- code: abcd1234
  label-en_US: Lorem Ipsum is simply dummied text of the printing and typesetting
    industry --> this line should not be here
ObjectMapper mapper = new ObjectMapper(new YAMLFactory().enable(MINIMIZE_QUOTES));

mapper.writeValue(Paths.get("path/to/file").toFile(), getData());

Solution

  • So you don't want long text to be wrapped over multiple lines, which should make you ponder if there is an option in YAMLFactory to control that.

    You then check the documentation, i.e. the javadoc of YAMLFactory, to see if there is anything useful for that. Looking through the list of methods, you notice the disable(YAMLGenerator.Feature f) and enable(YAMLGenerator.Feature f) methods and you ponder if there is a YAMLGenerator.Feature for what you want.

    Looking through the list of features, you find one called SPLIT_LINES, which is described as:

    Options passed to SnakeYAML that determines whether longer textual content gets automatically split into multiple lines or not.

    Feature is enabled by default to conform to SnakeYAML defaults as well as backwards compatibility with 2.5 and earlier versions.

    After doing a small victory dance at the prowess of your research skills ... ok, no you don't do that, because having had to be lead here shows lack of such skills, but you wow to yourself to try to improve your research skills in the future ... you add disable(SPLIT_LINES) to the code.

    YAMLFactory yamlFactory = YAMLFactory.builder()
            .enable(MINIMIZE_QUOTES)
            .disable(SPLIT_LINES)
            .build();
    ObjectMapper mapper = new ObjectMapper(yamlFactory);