英文:
How to set Java - SnakeYaml Dumperoptions to leave out Quotations and '|'?
问题
我在Java中使用Snakeyaml来转储一个Yaml文件,该文件稍后会被另一个应用程序解析。
输出的Yaml必须如下所示:
aKey: 1234
anotherKey: a string
thirdKey:
4321:
- some script code passed as a string
- a second line of code passed as a string
到目前为止,我最接近的设置是通过以下方式设置转储器选项:
DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setPrettyFlow(true);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
// ...
Map<String, Object> data = new LinkedHashMap<>();
Map<Integer, Object> thirdKey = new LinkedHashMap<>();
data.put("aKey", 1234);
data.put("anotherKey", "aString");
StringBuilder extended = new StringBuilder();
extended.append("- some script code passed as a string\n- a second line of code passed as a string\n");
String result = extended.toString();
thirdKey.put(4321, result);
data.put("thirdKey", thirdKey);
yaml.dump(data, writer);
然而,输出结果却是这样的:
aKey: 1234
anotherKey: a string
thirdKey:
4321: |
- some script code passed as a string
- a second line of code passed as a string
仅仅是|
符号阻止了我实现最终目标。
是否有办法设置转储选项以在不插入|
符号的情况下换行呢?
英文:
I am using Snakeyaml in Java to dump a Yaml-File which is later parsed by another Application.
The output-Yaml has to look like this:
aKey: 1234
anotherKey: a string
thirdKey:
4321:
- some script code passed as a string
- a second line of code passed as a string
So far, the closest i have come is by setting the dumper - options like this:
DumperOptions options = new DumperOptions();
options.setIndent(2);
options.setPrettyFlow(true);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
[...]
Map<String, Object> data = new LinkedHashMap<>();
Map<Integer, Object> thirdKey= new LinkedHashMap<>();
data.put("aKey", 1234);
data.put("anotherKey", "aString");
StringBuilder extended = new StringBuilder();
extended.append("- some script code passed as a string\n- a second line of code passed as a string\n");
String result = extended.toString();
thirdKey.put(4321, result);
data.put("thirdKey", thirdKey);
yaml.dump(data, writer);
The output, however, is like this:
aKey: 1234
anotherKey: a string
thirdKey:
4321: |
- some script code passed as a string
- a second line of code passed as a string
The mere | is what is separating me from achieving my final goal.
Is there any way to set the dumperoptions to break the lines like this without inserting a | symbol?
答案1
得分: 2
问题在于你将列表标记“-”生成为你内容的一部分。实际上它们并不是!它们是YAML语法的一部分。
由于在YAML中,你想要的是一个序列(YAML中表示列表的术语),你需要将一个列表放入你的结构中:
thirdKey.put(4321, Arrays.asList(
"作为字符串传递的一些脚本代码",
"作为字符串传递的第二行代码"));
英文:
The problem is that you generate the list markers -
as part of your content. They are not! They are part of the YAML syntax.
Since what you want in YAML is a sequence (YAML term for a list), you have to put a list into your structure:
thirdKey.put(4321, Arrays.asList(
"some script code passed as a string",
"a second line of code passed as a string"));
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论