From 0c1bb6e038e2c859422909d37810883f7be5444d Mon Sep 17 00:00:00 2001 From: InvalidJoker <0limitdev@gmail.com> Date: Mon, 3 Feb 2025 13:58:36 +0100 Subject: [PATCH] feat: location adapter --- .../kpaper/file/gson/LocalDataTypeAdapter.kt | 1 - .../kpaper/file/gson/LocationTypeAdapter.kt | 35 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 src/main/kotlin/cc/modlabs/kpaper/file/gson/LocationTypeAdapter.kt diff --git a/src/main/kotlin/cc/modlabs/kpaper/file/gson/LocalDataTypeAdapter.kt b/src/main/kotlin/cc/modlabs/kpaper/file/gson/LocalDataTypeAdapter.kt index adb4bf5..9092d95 100644 --- a/src/main/kotlin/cc/modlabs/kpaper/file/gson/LocalDataTypeAdapter.kt +++ b/src/main/kotlin/cc/modlabs/kpaper/file/gson/LocalDataTypeAdapter.kt @@ -11,7 +11,6 @@ class LocalDateAdapter : JsonSerializer, JsonDeserializer typeOfSrc: Type?, context: JsonSerializationContext? ): JsonElement { - // If you don't want null to appear at all, you can handle it differently return if (src == null) JsonNull.INSTANCE else JsonPrimitive(src.toString()) } diff --git a/src/main/kotlin/cc/modlabs/kpaper/file/gson/LocationTypeAdapter.kt b/src/main/kotlin/cc/modlabs/kpaper/file/gson/LocationTypeAdapter.kt new file mode 100644 index 0000000..62be552 --- /dev/null +++ b/src/main/kotlin/cc/modlabs/kpaper/file/gson/LocationTypeAdapter.kt @@ -0,0 +1,35 @@ +package cc.modlabs.kpaper.file.gson + +import com.google.gson.* +import org.bukkit.Bukkit +import org.bukkit.Location +import org.bukkit.World +import java.lang.reflect.Type + +class LocationTypeAdapter : JsonSerializer, JsonDeserializer { + override fun serialize(src: Location, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { + val jsonObject = JsonObject() + jsonObject.addProperty("world", src.world?.name ?: "world") + jsonObject.addProperty("x", src.x) + jsonObject.addProperty("y", src.y) + jsonObject.addProperty("z", src.z) + jsonObject.addProperty("yaw", src.yaw) + jsonObject.addProperty("pitch", src.pitch) + return jsonObject + } + + @Throws(JsonParseException::class) + override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Location { + val jsonObject = json.asJsonObject + val worldName = jsonObject["world"].asString + val world: World = Bukkit.getWorld(worldName) ?: throw JsonParseException("World '$worldName' not found") + + val x = jsonObject["x"].asDouble + val y = jsonObject["y"].asDouble + val z = jsonObject["z"].asDouble + val yaw = jsonObject["yaw"].asFloat + val pitch = jsonObject["pitch"].asFloat + + return Location(world, x, y, z, yaw, pitch) + } +} \ No newline at end of file