SnakeYaml dump function writes with single quotes

梦想的初衷 提交于 2021-02-08 06:56:47

问题


Consider the following code:

public void testDumpWriter() {
Map<String, Object> data = new HashMap<String, Object>();
data.put("NAME1", "Raj");
data.put("NAME2", "Kumar");

Yaml yaml = new Yaml();
FileWriter writer = new FileWriter("/path/to/file.yaml");
for (Map.Entry m : data.entrySet()) {
            String temp = new StringBuilder().append(m.getKey()).append(": ").append(m.getValue()).toString();
            yaml.dump(temp, file);
        }
}

The output of the above code is

'NAME1: Raj'
'NAME2: Kumar'

But i want the output without the single quotes like

NAME1: Raj
NAME2: Kumar

This thing is very comfortable for parsing the file. If anyone have solution, please help me to fix. Thanks in advance


回答1:


Well SnakeYaml does exactly what you tell it to: For each entry in the Map, it dumps the concatenation of the key, the String ": ", and the value as YAML document. A String maps to a Scalar in YAML, and since the scalar contains a : followed by space, it must be quoted (else it would be a key-value pair).

What you actually want to do is to dump the Map as YAML mapping. You can do it like this:

public void testDumpWriter() {
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("NAME1", "Raj");
    data.put("NAME2", "Kumar");

    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    Yaml yaml = new Yaml(options);
    FileWriter writer = new FileWriter("/path/to/file.yaml");
    yaml.dump(data, writer);
}


来源:https://stackoverflow.com/questions/46913105/snakeyaml-dump-function-writes-with-single-quotes

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