Serializing Location Objects

Apr 14, 2021
Serializing Location Objects
  • Serializing Location Objects

    Learn how to serialize & deserialize Location objects for use with config files!

    What is serialization and why does it matter?(top)

    Sometime you want to save objects to a config file. For this you need to serialize it. Serialization can be done in many ways, like base encoding the whole java object or just creating a yaml or String representation of it.

    When you need to get the data you saved to your config you will need to deserialize it. This means that you have to deserialize and reconstruct your object based on the data you get from your config.

    Luckily Bukkit got you back and already implemented these serialization and deserialization mechanisms in some cases already. Also on the Location class.

    The Location object(top)

    Serializing and deserializing of a Location object is a nobrainer.
    The Location class implements the ConfigurationSerializable interface. This interface provides a serialize() method which will return the object serialized to a Map<String, Object>. The Location also have a Constructor to create a Location from one of those Maps. But you don't even need to care about this, because Bukkit does everything for you.

    All you need to do is save your Location object to your config. Yes your object. No need to unwrap the object in any way.

    Code (Java):
            Location location = new Location(Bukkit.getWorld("world"), 100, 200, 300, 400, 500);
            config.set("some.location", location);
    That it. Yes. All you have to do is just set some key and pass your location.

    Now you have something like this in your config:
    Code (YAML):
    : org.bukkit.Location
    : world
    : 100.0
    : 200.0
    : 300.0
    : 500.0
    : 400.0
    The == key indicates which class this object is made from. It tells bukkit which class it should reconstruct when the config is loaded.

    That's why loading a Location is as simple as this:
    Code (Java):
            Location location = config.getObject("some.location", Location.class);
            Location location = (Location) config.get("some.location"); // Legacy
    Yes that's all. You should always take the first method. This one also casts the object already to the one you want. However the second method is required if you are using some dinosaur versions (Looking at you 1.8 developers!)...

    Hint: You can to the same with ItemStacks, Vector, BlockVector, Color, PotionEffect, FireworkEffect, Pattern, AttributeModifier and BoundingBox. All these classes implement the magic ConfigurationSerializable interface.

    Now go out there and make the world a better one! You can also implement this interface by yourself.
  • Loading...
  • Loading...