有一个简单的 yml 文件 test.yml
如下
color: 'red'
我按如下方式加载和转储文件
final DumperOptions yamlOptions = new DumperOptions();
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(yamlOptions);
Object result = yaml.load(new FileInputStream(new File("test.yml")));
System.out.println(yaml.dump(result));
我希望得到
color: 'red'
但是,在转储期间,序列化程序会忽略引号并打印
color: red
如何让序列化器也打印原始报价?
最佳答案
How can I make the serializer to print the original quotes too?
不适用于高级 API。引用the spec :
The scalar style is a presentation detail and must not be used to convey content information, with the exception that plain scalars are distinguished for the purpose of tag resolution.
高级 API 实现了整个 YAML 加载过程,按照规范的要求,仅向您提供 YAML 文件的内容,而不提供任何有关演示文稿详细信息的信息。
话虽这么说,您可以使用保留演示文稿详细信息的低级 API:
final Yaml yaml = new Yaml();
final Iterator<Event> events = yaml.parse(new StreamReader(new UnicodeReader(
new FileInputStream(new File("test.yml"))).iterator();
final DumperOptions yamlOptions = new DumperOptions();
final Emitter emitter = new Emitter(new PrintWriter(System.out), yamlOptions);
while (events.hasNext()) emitter.emit(events.next());
但是,请注意,即使这样也不会保留输入的每个演示细节(例如,不会保留缩进和注释)。 SnakeYaml 不是往返的,因此无法保留确切的输入布局。
关于java - 使用 SnakeYaml 转储带引号的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55268892/