使用 SnakeYaml 转储带引号的值
Dumping values with quotes with SnakeYaml
有一个简单的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 不是往返的,因此无法保留准确的输入布局。
有一个简单的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 不是往返的,因此无法保留准确的输入布局。