gpt4 book ai didi

java - SnakeYAML 转储嵌套键

转载 作者:行者123 更新时间:2023-12-02 01:48:05 26 4
gpt4 key购买 nike

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

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

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

当我使用时

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}

谢谢!

最佳答案

使用 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 类中的字段顺序,但我不确定。

关于java - SnakeYAML 转储嵌套键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57444633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com