How can I set/get a HashMap in a YAML configuration file?

BLuFeNiX picture BLuFeNiX · Jul 21, 2013 · Viewed 7k times · Source

I am making my first bukkit plugin. I would like to programmatically create a YAML file that represents a HashMap. How can I set and get this data structure?

The HashMap parameters look like <Signature, Location>, where Signature is my class that stores 4 integers, and Location is org.bukkit.Location

I think I would like the YAML file to look like this, but I am not sure if this structure is best:

MyPlugin:
    ListOfData:
        - signature: [1,2,3,4]    # this is a unique set of 4 integers
          location: [122,64,254]  # non-unique set of 3 integers
        - signature: [4,2,1,2]
          location: [91,62,101]
        - signature: [3,3,1,3]
          location: [190,64,321]

Signature can be modified as necessary, and I can create a wrapper for Location if necessary.

Thanks!

Answer

Iain picture Iain · Jul 22, 2013

This is a suggested solution. I don't know if it is the best way...:) You may want to consider this as your yaml structure:

MyPlugin:
    ListOfData:
        '[1,2,3,4]': '[122,64,254]'
        '[4,2,1,2]': '[91,62,101]'
        '[3,3,1,3]': '[190,64,321]'
        anothersignature:anotherlocation
        ...

This will let you read the "ListOfData" in using the normal technique for reading hash map from a YAMLConfiguration (see below).

You'll have to treat the incoming information from the file as a HashMap of <String, String> and do any translation (e.g. turn 122,64,254 into a location) you need from there.

For reading a HashMap:

this.getConfig().getConfigurationSection("path.to.map").getValues(false)

For writing a HashMap (saveConfig() will still need to be called to write to disk):

this.getConfig().createSection("path.to.map", MyMap)

There's some details and subtleties here, its worth reading these carefully (same page, but different non-contiguous sections):

http://wiki.bukkit.org/Configuration_API_Reference#HashMaps http://wiki.bukkit.org/Configuration_API_Reference#HashMaps_2