如何使用Snakeyaml在yaml文件中获取所有子代(及其子代)

时间:2018-08-21 20:11:53

标签: java yaml snakeyaml

所以我遇到过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提供的哈希表列表

谢谢

1 个答案:

答案 0 :(得分:0)

您可以创建代表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://github.com/KenavR/snakeyaml-example

相关问题