Search code examples
javalistserializationjacksonyaml

How to print a Java List to a Yaml List in brace ([ ]) format, using Jackson yaml


I am trying to find a way to print Java ArrayLists to Yaml lists, in the following format:

[list-element1,list-element2,list-element3...]

However,I have only managed to print them into Yaml lists in the alternative format:

-list-element1
-list-element2
-list-element3

Is there a way that the first can be done with a setting in Jackson? I know it can be done with SnakeYaml, but do not want to follow this path.

In case the answer to this question is no, I also have created a custom serializer, which serializes the Java list to the desired format ([list-element1,list-element2,list-element3...]) and adds it to the jsonGenerator passed to the serialize(...) method by calling

jasonGenerator.writeStringField("ArrayList", list_string.toString()).

However, when I call

String yamlString = mapper.writeValueAsString(object_to_serialize)

the output is in the form of

'[list-element1,list-element2,list-element3...]'

(quoted), even though minimize quotes is enabled in the respective YAMLFactory. Is there another solution, besides parsing yamlString and replacing the offending characters?


Solution

  • It seems that there is no other solution, and is most likely related to the process of java-to-yaml serialization. The same behavior is exhibited, not only when I try to output lists with brace characters, but also in strings containing colons, and in general it seems that whenever the library parses a string that violates some conditions (e.g beginning with blanks, or including a character that it uses for its yaml output), it wraps it with quotation marks.