【问题标题】:Snakeyaml - How to have custom control on the flow styleSnakeyaml - 如何对流样式进行自定义控制
【发布时间】:2018-06-25 02:47:46
【问题描述】:

我正在尝试使用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?我应该使用其他方式来构建地图吗?

【问题讨论】:

    标签: java yaml snakeyaml


    【解决方案1】:

    您似乎不能用DumperOptionsmappingssequences 指定不同的流样式。

    但是您可以做的是覆盖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]
    

    【讨论】:

    • 我留下了一个编辑请求。我认为 flowStyle 在某个时候从 Boolean 变成了 DumperOptions.FlowStyle。我的编辑反映了这一变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 2013-06-28
    • 1970-01-01
    • 2010-09-09
    相关资源
    最近更新 更多