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?
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.
Support for reading and writing YAML-encoded data via Jackson abstractions.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With