简体   繁体   English

用杰克逊写yaml?

[英]Use Jackson to write yaml?

I'm using Jackson to read and modify yaml files. 我正在使用Jackson阅读和修改yaml文件。 Works great. 效果很好。 I can't find the magic incantations needed to write the yaml, though. 但是,我无法找到编写yaml所需的神奇咒语。

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. 我确信这是作家,JsonGenerators和其他东西的组合。 Anyone got sample code? 有人得到示例代码吗?

For v2.8.3 the following should work: 对于v2.8.3,以下内容应该有效:

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);

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM