SnakeYaml dumping from String First Line
I am trying to create a yaml file from pure java String. However, my created yaml file has the initial line as:
Rest of the yaml file is just fine but the first line is pretty interesting. My DumperOptions are as follows;
DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml yaml = new Yaml(options); // Build the complex String here. String dump = yaml.dump(builder.toString());
Yes, I can remove the initial line from StringBuilder directly, but I would like to know the solution or even the cause of the problem.
There is no problem, if you dump a single string to a YAML file the library can do so in multiple ways. Here it does so in literal block mode using a block indention indicator. You requested the block style yourself (DumperOptions.FlowStyle.BLOCK), so the block indicator (|) has to be there, but the indentation indicator might or might not be necessary.
"The rest of the YAML file is just fine" is just because that is your single Java string indented by two spaces.
YAML emitters need to do something special if a string starts with a space and/or when there are special characters (e.g. newlines) in a string. They can either use quoting (single or double) or revert to block literals (using |). Block literals need to have number to indicate the indentation level if the string scalar starts with one or more blanks, as otherwise a too big indentation level would be calculated from the first line. Normally the decision on what to use (plain style with or without quotes or block style) is made after analysis of the string and depending on the context. In your case you force it to block style.
You might be able to get the 2 from the first line by stripping any leading whitespace from the string, but to get rid of the |, you probably need to have a string without newlines and remove the setting of the BLOCK flow style.