【问题标题】:SnakeYAML Dump nested keySnakeYAML 转储嵌套键
【发布时间】:2019-12-18 01:20:36
【问题描述】:

我正在使用SnakeYAML 作为项目的 YAML 解析器,但我不知道如何设置嵌套的键。例如,这是一个包含嵌套键的 YAML 文件。

control:
  advertising:
    enabled: true
logging:
  chat: true
  commands: true
  format: '%id% %date% %username% | %value%'

我的目标是能够轻松地将路径 control.advertising.enabledany 其他路径设置为任何值。

当我使用时

void Set(String key, Object value, String configName){
    Yaml yaml = new Yaml();
    OutputStream oS;
    try {
        oS = new FileOutputStream(main.getDataFolder() + File.separator + configName);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    }
    Map<String, Object> data = new HashMap<String, Object>();
    // set data based on original + modified
    data.put(key, value);
    String output = yaml.dump(data);

    try {
        oS.write(output.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

设置值,而不是获取

logging:
  chat: true
  commands: true
  format: '%id% %date% %username% | %value%'

整个 yaml 文件被清除,我只得到 {logging.chat: false}

谢谢!

【问题讨论】:

  • 好吧,你永远不会加载旧的 YAML 文件;相反,您只需创建一些数据并将其转储,当然它不包含以前的值。您是否尝试过为 YAML 的内容定义 POJO,然后使用 loadAs 将 YAML 加载到该 POJO 中?这将使设置值并将其写出来变得非常简单。
  • 我不太明白你现在想让我做什么。我有这个pastebin.com/LA1585cv

标签: java yaml snakeyaml


【解决方案1】:

用 Java 类定义你的结构:

public class Config {
    public static class Advertising {
        public boolean enabled;
    }
    public static class Control {
        public Advertising advertising;
    }
    public static class Logging {
        public boolean chat;
        public boolean commands;
        public String format;
    }

    Control control;
    Logging logging;
}

然后你可以这样修改:

Yaml yaml = new Yaml();
Config config = yaml.loadAs(inputStream, Config.class);
config.control.advertising.enabled = false;
String output = yaml.dump(config);

请注意,以这种方式加载和保存 YAML 数据可能会弄乱映射键的顺序,因为不会保留此顺序。我假设输出顺序将根据 Java 类中的字段顺序,但我不确定。

【讨论】:

    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2013-08-14
    • 2019-08-11
    • 2014-12-18
    • 2018-04-05
    • 2012-12-19
    相关资源
    最近更新 更多