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?"));
CodePudding user response:
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
CodePudding user response:
If you really want to get as list, you can use getConfig().getList("Streuzel")
that will return a list of LinkedHashMap<>
. You can use it like that:
LinkedHashMap<String, Object> myObj = (LinkedHashMap<String, Object>) getConfig().getList("Streuzel").get(0);
Bukkit.broadcastMessage(ChatColor.YELLOW myObj.get("name") ChatColor.WHITE ", " ChatColor.GREEN myObj.get("coords"));
But, this is not recommended. It's better to use configuration section like that:
Streuzel:
1:
name: Home
coords: X:-1 Y:79 Z:3
2:
name: Nether
coords: X:23 Y:65 Z:-19
Then, you can use them like that:
Bukkit.broadcastMessage(ChatColor.YELLOW getConfig().getString("Streuzel.1.name") ChatColor.WHITE ", " ChatColor.GREEN getConfig().getString("Streuzel.1.coords"));
This way, with section, make it so much easier to get all content. If you want to find all sections, do like that:
// here is the config with all keys
ConfigurationSection globalSection = getConfig().getConfigurationSection("Streuzel");
for(String keys : globalSection.getKeys(false)) { // all kays: "1", "2" ...
ConfigurationSection objSection = globalSection.getConfigurationSection(keys);
// here you can load your object, log it or get content with objSection.getString()
}