用杰克逊写yaml?

时间:2015-01-01 20:00:06

标签: java json jackson yaml

我使用Jackson来阅读和修改yaml文件。效果很好。但是,我无法找到编写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.

我确定它是作家,JsonGenerators和其他东西的组合。有人拿到样本代码吗?

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

尝试:

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.