Search code examples
javaarraysyamlbukkit

What path to use in Java for YAML arrays with multiple objects?


I am currently trying to figure out how to get a String from my config.yml into my Java code. More specifically, which path to use to get "Home", "X:-1 Y:79 Z:3", "Nether" or "X:23 Y:65 Z:-19" extracted into my Java code. I already tried getConfig().getString("Streuzel[0].name"), but that didn't work.

YAML: (Array with multiple objects)

Streuzel:
    -
        name: Home
        coords: X:-1 Y:79 Z:3
    -
        name: Nether
        coords: X:23 Y:65 Z:-19

Java:

Bukkit.broadcastMessage(ChatColor.YELLOW + getConfig().getString("path?") + ChatColor.WHITE + ", " + ChatColor.GREEN + getConfig().getString("path?"));

Solution

  • Actually, Streuzel is a List, not an array, so you need to use getList(String) instead of getString(String). In your case, each element of this list is a Map<String, String>. So, if you don't care about type cast safety (because yaml can be edited by humans and it potentially can lose structure), you can use something like this:

    ((Map<String, String>)config.getList("Streuzel").get(0)).get("name") // Home
    

    But ideally, you could either check if "Streuzel" is a list and if it contains a Map, or try...catch ClassCastException.

    About an answer that got posted 3 minutes ago: Streuzel is a List, not a Map!
    EDIT: they fixed it