所以我和snakeyaml有过接触。我知道如何使用java yaml.load(inputStream);
获取它们的键,它将返回一个字符串和一个对象的哈希图。只是为了演示,我有一个带有值的yaml文件:
player:
randie:
score: 4
当我使用
File file = new File("test")
FileInputStream stream = new FileInputStream(file);
Map<String, Object> map = yaml.load(stream);
for (String str : map.keySet()) {
System.out.println(map.get(str));
}
输出将为:
{randie={score=4}}
我遇到了其他堆栈溢出问题,比如this
我希望在最内层的“嵌套”值中获得一个值,而不使用the correct answer in the thread提供的哈希图列表
谢谢
发布于 2018-08-22 05:46:20
您可以创建表示yaml文件结构的类,然后以正确的格式加载它。
public class Result {
private Player player;
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
}
public class Player {
private Randie randie;
public Randie getRandie() {
return randie;
}
public void setRandie(Randie randie) {
this.randie = randie;
}
}
public class Randie {
private int score;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
然后使用loadAs
函数加载它。
public class YamlDataInterpreter {
public static void main(String[] args) {
YamlDataInterpreter intepreter = new YamlDataInterpreter();
intepreter.interpretYaml();
}
public void interpretYaml() {
InputStream stream = this.getClass().getClassLoader()
.getResourceAsStream("data.yml");
Yaml yaml = new Yaml();
Result res = yaml.loadAs(stream, Result.class);
System.out.println(res.getPlayer().getRandie().getScore());
}
}
https://stackoverflow.com/questions/51956039
复制相似问题