使用 SnakeYaml 解析嵌套 YAML 对象的点分隔键

Parsing dot separated keys to nested YAML objects with SnakeYaml

提问人:Scott 提问时间:11/4/2023 更新时间:11/4/2023 访问量:21

问:

我有以下几点HashMap

 Map<String, Object> map = new HashMap<>();
 map.put("a.b", "c");
 map.put("a.d", "e");

以及以下代码,使用 SnakeYAML 将映射写入 YAML 文件

 DumperOptions options = new DumperOptions();
 options.setDefaultFlowStyle(FlowStyle.BLOCK);
 options.setPrettyFlow(true);
 Yaml yaml = new Yaml(options);
 String path = System.getProperty("user.dir") + "file.yaml";

 try (FileWriter fileWriter = new FileWriter(path)) {
   yaml.dump(map, fileWriter);
 } catch (IOException e) {
   throw new RuntimeException(e);
 }

之后,我可以看到该文件包含以下内容cat file.yaml

a.b: c
a.d: e

但是,我希望格式化输出,以便点分隔键实际上是嵌套对象

a:
  b: c
  d: e

我试过更改和更改 ,但到目前为止我没有运气。options.setIdent()FlowStyleFLOW

我怎样才能在Java中做到这一点?或者我是否改变了我的方法并使用了另一种方法?SnakeYAML

java 蛇类

评论


答: 暂无答案