Dumping values with quotes with SnakeYaml

ⅰ亾dé卋堺 提交于 2021-02-05 07:45:07

问题


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

I expect to get

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?


回答1:


How can I make the serializer to print the original quotes too?

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.

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.

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

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.



来源:https://stackoverflow.com/questions/55268892/dumping-values-with-quotes-with-snakeyaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!