Snakeyaml - 如何对流样式进行自定义控制

Sar*_*h N 5 java yaml snakeyaml

我正在尝试使用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);
Run Code Online (Sandbox Code Playgroud)

第一个选项输出这个,它为 Parent-2 提供了正确的格式,但不为 Parent-1 提供了正确的格式:

Version: 2.0
Parent-1: {Criteria-1: 2, Criteria-2: 1}
Parent-2:
- [Criteria-1, Criteria-2, 1]
Run Code Online (Sandbox Code Playgroud)

第二个选项输出这个,它为 Parent-1 提供了正确的格式,但没有为 Parent-2 提供:

Version: 2.0
Parent-1:
  Criteria-1: 2
  Criteria-2: 1
Parent-2:
- - Criteria-1
  - Criteria-2
  - 1
Run Code Online (Sandbox Code Playgroud)

我需要的输出是:

Version: 2.0
Parent-1:
  Criteria-1: 2
  Criteria-2: 1
Parent-2:
- [Criteria-1, Criteria-2, 1]
Run Code Online (Sandbox Code Playgroud)

实际文件包含锚点和别名,因此我无法分两次转储 yaml。有没有办法自定义地图的哪些部分应该是FLOW,哪些应该是BLOCK?我应该使用另一种方式来构建地图吗?

zep*_*lin 6

您似乎无法为mappingssequenceswith指定不同的流程样式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);
Run Code Online (Sandbox Code Playgroud)

这应该会给你你想要的输出:

Version: 2.0
Parent-1:
  Criteria-1: 2
  Criteria-2: 1
Parent-2:
- [Criteria-1, Criteria-2, 1]
Run Code Online (Sandbox Code Playgroud)