我正在尝试使用snakeyaml在java中创建YAML文件,但无法获取我需要的格式。使用
DumperOptions.FlowStyle.BLOCK
时,部分子项的格式正确,而使用默认 DumperOptions.FlowStyle.AUTO
时,其他部分的格式正确。这是我的意思的一个最小例子:
Map<String,Integer> children1 = new LinkedHashMap();
children1.put("Criteria-1", 2);
children1.put("Criteria-2",1);
List<List<Object>> children2 = new ArrayList<>();
List<Object> list = new ArrayList<>();
list.add("Criteria-1");
list.add("Criteria-2");
list.add(new Integer(1));
children2.add(list);
Map<String,Object> map = new LinkedHashMap();
map.put("Version",2.0);
map.put("Parent-1",children1);
map.put("Parent-2",children2);
//Style 1 - AUTO - Correct format for Parent-2
Yaml yaml1 = new Yaml();
String style1 = yaml1.dump(map);
System.out.println(style1);
//Style 2 - BLOCK - Correct format for Parent-1
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml2 = new Yaml(options);
String style2 = yaml2.dump(map);
System.out.println(style2);
第一个选项输出此内容,这为 Parent-2 提供了正确的格式,但为 Parent-1 提供了正确的格式:
Version: 2.0
Parent-1: {Criteria-1: 2, Criteria-2: 1}
Parent-2:
- [Criteria-1, Criteria-2, 1]
第二个选项输出此内容,这为 Parent-1 提供了正确的格式,但为 Parent-2 提供了正确的格式:
Version: 2.0
Parent-1:
Criteria-1: 2
Criteria-2: 1
Parent-2:
- - Criteria-1
- Criteria-2
- 1
我需要的输出是:
Version: 2.0
Parent-1:
Criteria-1: 2
Criteria-2: 1
Parent-2:
- [Criteria-1, Criteria-2, 1]
实际文件包含锚点和别名,因此我无法两次转储 yaml。有没有办法自定义地图的哪些部分应该是
FLOW
,哪些部分应该是BLOCK
?我应该使用其他方法来构建地图吗?
您似乎无法使用
mappings
为 sequences
和 DumperOptions
指定不同的流程样式。
但是您可以做的是覆盖
Representer
以强制映射的非默认流程样式,如下所示:
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.AUTO);
Yaml yaml2 = new Yaml(new Representer() {
@Override
protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) {
return super.representMapping(tag, mapping, false);
}
},options);
String style2 = yaml2.dump(map);
System.out.println(style2);
这应该给你你想要的输出:
Version: 2.0
Parent-1:
Criteria-1: 2
Criteria-2: 1
Parent-2:
- [Criteria-1, Criteria-2, 1]
我也面临着类似的挑战。对于我的应用程序,我想要以下 yaml 样式(块和流的组合),但是我无法解决该问题。我已经尝试过 Snakeyml jar 和使用 YAMLFactory,但它们都不起作用。 需要有关该问题的帮助。
name: srlceos01
topology:
nodes:
srl:
kind: nokia_srlinux
image: ghcr.io/nokia/srlinux
ceos:
kind: ceos
image: ceos:4.25.0F
links:
- endpoints: ["srl:e1-1", "ceos:eth1"]