Skip to content

Commit

Permalink
feat: location adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
InvalidJoker committed Feb 3, 2025
1 parent eed5cc9 commit 0c1bb6e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ class LocalDateAdapter : JsonSerializer<LocalDate>, JsonDeserializer<LocalDate>
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())
}

Expand Down
35 changes: 35 additions & 0 deletions src/main/kotlin/cc/modlabs/kpaper/file/gson/LocationTypeAdapter.kt
Original file line number Diff line number Diff line change
@@ -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<Location>, JsonDeserializer<Location> {
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)
}
}

0 comments on commit 0c1bb6e

Please sign in to comment.