Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Jackson to write yaml?

I'm using Jackson to read and modify yaml files. Works great. I can't find the magic incantations needed to write the yaml, though.

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'm sure it's some combination of writers, JsonGenerators, and something else. Anyone got sample code?

like image 925
ccleve Avatar asked Jan 01 '15 20:01

ccleve


People also ask

Can Jackson parse YAML?

Jackson is an extremely popular Java-based library used for parsing and manipulating JSON and XML files. Needless to say, it also allows us to parse and manipulate YAML files in a similar fashion to how we're already used to doing with the two previously mentioned formats.

What is Jackson Dataformat YAML?

Support for reading and writing YAML-encoded data via Jackson abstractions.

How do I create a YAML file in Java?

The Yaml instance introduces us to methods, such as load() which allow us to read and parse any InputStream , Reader or String with valid YAML data: InputStream inputStream = new FileInputStream(new File("student. yml")); Yaml yaml = new Yaml(); Map<String, Object> data = yaml. load(inputStream); System.

How do I edit a YAML file in Java?

You will need YAMLMapper (from jackson-databind-yaml ) which is the YAML-specific implementation of ObjectMapper (from jackson-databind ). ObjectMapper objectMapper = new YAMLMapper(); Then it is easy: just read the YAML file, modify the contents, and write the YAML file.


1 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);
like image 65
gilbertpilz Avatar answered Sep 23 '22 00:09

gilbertpilz