首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用snakeyaml获取yaml文件中的所有子项(及其子项)

如何使用snakeyaml获取yaml文件中的所有子项(及其子项)
EN

Stack Overflow用户
提问于 2018-08-22 04:11:53
回答 1查看 2K关注 0票数 0

所以我和snakeyaml有过接触。我知道如何使用java yaml.load(inputStream);获取它们的键,它将返回一个字符串和一个对象的哈希图。只是为了演示,我有一个带有值的yaml文件:

代码语言:javascript
复制
player:
  randie:
    score: 4

当我使用

代码语言:javascript
复制
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));
}

输出将为:

代码语言:javascript
复制
{randie={score=4}}

我遇到了其他堆栈溢出问题,比如this

我希望在最内层的“嵌套”值中获得一个值,而不使用the correct answer in the thread提供的哈希图列表

谢谢

EN

回答 1

Stack Overflow用户

发布于 2018-08-22 05:46:20

您可以创建表示yaml文件结构的类,然后以正确的格式加载它。

代码语言:javascript
复制
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函数加载它。

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51956039

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档