java 用Jackson写yaml?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27734153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:18:38  来源:igfitidea点击:

Use Hymanson to write yaml?

javajsonHymansonyaml

提问by ccleve

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

我正在使用 Hymanson 读取和修改 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.

I'm sure it's some combination of writers, JsonGenerators, and something else. Anyone got sample code?

我确信它是作家、JsonGenerators 和其他东西的某种组合。有人有示例代码吗?

回答by gilbertpilz

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

回答by ccleve

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.