diff --git a/src/main/java/com/fasterxml/jackson/dataformat/yaml/YAMLGenerator.java b/src/main/java/com/fasterxml/jackson/dataformat/yaml/YAMLGenerator.java index 9c527cf..9a3022c 100644 --- a/src/main/java/com/fasterxml/jackson/dataformat/yaml/YAMLGenerator.java +++ b/src/main/java/com/fasterxml/jackson/dataformat/yaml/YAMLGenerator.java @@ -91,7 +91,16 @@ public enum Feature // implements FormatFeature // for 2.7 * * @since 2.8.2 */ - ALWAYS_QUOTE_NUMBERS_AS_STRINGS(false) + ALWAYS_QUOTE_NUMBERS_AS_STRINGS(false), + + /** + * Whether for string containing newlines a literal block style + * should be used. This automatically enabled when {@link #MINIMIZE_QUOTES} is set. + *

+ * The content of such strings is limited to printable characters according to the rules of + * literal block style. + */ + LITERAL_BLOCK_STYLE(false) ; protected final boolean _defaultState; @@ -488,6 +497,8 @@ public void writeString(String text) throws IOException,JsonGenerationException } else { style = STYLE_PLAIN; } + } else if (Feature.LITERAL_BLOCK_STYLE.enabledIn(_formatFeatures) && text.indexOf('\n') >= 0) { + style = STYLE_LITERAL; } _writeScalar(text, "string", style); } diff --git a/src/test/java/com/fasterxml/jackson/dataformat/yaml/SimpleGenerationTest.java b/src/test/java/com/fasterxml/jackson/dataformat/yaml/SimpleGenerationTest.java index 3f9830d..2afd2ec 100644 --- a/src/test/java/com/fasterxml/jackson/dataformat/yaml/SimpleGenerationTest.java +++ b/src/test/java/com/fasterxml/jackson/dataformat/yaml/SimpleGenerationTest.java @@ -332,6 +332,31 @@ public void testNonQuoteNumberStoredAsString() throws Exception "key: 2.0.1.2.3", yaml); } + public void testLiteralBlockStyle() throws Exception + { + YAMLFactory f = new YAMLFactory(); + // verify default settings + assertFalse(f.isEnabled(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE)); + + f.configure(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE, true); + + YAMLMapper mapper = new YAMLMapper(f); + + Map content = new HashMap(); + content.put("text", "Hello\nWorld"); + String yaml = mapper.writeValueAsString(content).trim(); + + assertEquals("---\n" + + "text: |-\n Hello\n World", yaml); + + content.clear(); + content.put("text", "Hello World"); + yaml = mapper.writeValueAsString(content).trim(); + + assertEquals("---\n" + + "text: \"Hello World\"", yaml); + } + /* /********************************************************************** /* Helper methods