問題描述
有一個簡單的yml文件test.yml
如下
Having a simple yml file test.yml
as follows
color: 'red'
我按如下方式加載和轉儲文件
I load and dump the file as follows
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'
但是,在轉儲期間,序列化程序會忽略引號并打印
However, the during the dump, the serializer leaves out the quotes and prints
color: red
如何讓序列化程序也打印原始引號?
How can I make the serializer to print the original quotes too?
推薦答案
如何讓序列化程序也打印原始引號?
How can I make the serializer to print the original quotes too?
不使用高級 API.引用規范:
Not with the high-level API. Quoting 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 文件的內容,而沒有任何有關表示細節的信息.
The high-level API implements the whole YAML loading process, giving you only the content of the YAML file, without any information about presentation details, as required by the spec.
話雖如此,您可以使用保留演示詳細信息的低級 API:
That being said, you can use the low level API which preserves presentation details:
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 不是往返的,因此無法保留準確的輸入布局.
However, be aware that even this will not preserve every presentation detail of your input (e.g. indentation and comments will not be preserved). SnakeYaml is not round-tripping and therefore unable to preserve the exact input layout.
這篇關于使用 SnakeYaml 轉儲帶引號的值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!