Search code examples
javayamlbukkit

How to load tree/indexes from .yaml file using the Bukkit API?


How do I load tree/indexes from a YAML file in Bukkit? This is the file I want to grab all the values from:

groups:
  myGroup1:
    prefix: [test]
    permissions:
      - test
  myGroup2:
    prefix: [test2]
    permissions:
      - test2

This YAML file is a configuration, where users can add as many groups as they want so it is impossible to collect things like YamlConfiguration.getString("groups.myGroup1.[..])").

I need to have list of all things in "groups:", so it should look like YamlConfiguration.getString("groups.%groupName%.[..])"). Does someone know how to collect all the things after "groups:" (It can just be the group names) Thanks for the help!


Solution

  • Once you've loaded your YAML file and have an instance of YamlConfiguration you can use getKeys(boolean) to get the list of keys in the current section.

    If the parameter is true, then all the keys will be retrieved recursively. If it is false, then it will only get the top level keys. So calling yml.getConfigurationSection("groups").getKeys(false) on your example file would produce the following result:

    [myGroup1, myGroup2]
    

    In your case, using that to parse the yaml file would look something like this:

    ConfigurationSection section = yml.getConfigurationSection("groups");
    for (String group : section.getKeys(false)) {
        List<String> prefixes = section.getStringList("prefix");
        List<String> permissions = section.getStringList("permissions");
    }