我正在尝试用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?我应该使用另一种方法来构建地图吗?
发布于 2018-01-16 20:57:16
看起来您不能使用DumperOptions为mappings和sequences指定不同的流样式。
但您可以做的是覆盖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]https://stackoverflow.com/questions/48280482
复制相似问题