Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Class for serializing Locations (Bukkit)
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.util.NumberConversions;
public class LocationSerializable extends Location implements ConfigurationSerializable {
public LocationSerializable(World world, double x, double y, double z) {
super(world, x, y, z);
}
public LocationSerializable(World world, double x, double y, double z, float yaw, float pitch) {
super(world, x, y, z, yaw, pitch);
}
public LocationSerializable(String world, double x, double y, double z) {
super(Bukkit.getWorld(world), x, y, z);
}
public LocationSerializable(String world, double x, double y, double z, float yaw, float pitch) {
super(Bukkit.getWorld(world), x, y, z, yaw, pitch);
}
public Map<String, Object> serialize() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("world", super.getWorld().getName());
map.put("x", super.getX());
map.put("y", super.getY());
map.put("z", super.getZ());
if(super.getYaw() != 0) map.put("yaw", super.getYaw());
if(super.getPitch() != 0) map.put("pitch", super.getPitch());
return map;
}
public static LocationSerializable deserialize(Map<String, Object> map) {
if(!isValid(map)) return null;
return new LocationSerializable(Bukkit.getWorld(String.valueOf(map.get("world"))),
NumberConversions.toDouble(map.get("x")),
NumberConversions.toDouble(map.get("y")),
NumberConversions.toDouble(map.get("z")),
map.containsKey("yaw") ? NumberConversions.toFloat(map.get("yaw")) : 0,
map.containsKey("pitch") ? NumberConversions.toFloat(map.get("pitch")) : 0);
}
private static boolean isValid(Map<String, Object> map) {
return map.containsKey("x") && map.containsKey("y") && map.containsKey("z");
}
}
//Add this in your main class:
static {
ConfigurationSerialization.registerClass(LocationSerializable.class);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.