Use Jackson to write yaml?

I am using Jackson to read and modify yaml files. It works great. I can’t find the magic spells needed to write the barley.

ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); ObjectNode root = (ObjectNode)mapper.readTree(yamlFileIn); // modify root here mapper.writeValue(yamlFileOut, root); // writes json, not yaml. not sure why. 

I am sure this is a combination of writers, JsonGenerators and something else. Has anyone got sample code?

+6
source share
2 answers

For v2.8.3, the following should work:

 YAMLFactory yf = new YAMLFactory(); ObjectMapper mapper = new ObjectMapper(yf); ObjectNode root = (ObjectNode) mapper.readTree(yamlFileIn); // modify root here FileOutputStream fos = new FileOutputStream(yamlFileOut); SequenceWriter sw = mapper.writerWithDefaultPrettyPrinter().writeValues(fos); sw.write(root); 
+3
source

Try:

 YAMLFactory yf = new YAMLFactory(); ObjectMapper mapper = new ObjectMapper(yf); ObjectNode root = (ObjectNode) mapper.readTree(yamlFileIn); // modify root here FileOutputStream fos = new FileOutputStream(yamlFileOut); yf.createGenerator(fos).writeObject(root); // works. yay. 
+1
source

Source: https://habr.com/ru/post/980408/


All Articles