From e95ab413de0b9c7bbe6d9bf16a1e28d4a0dfbbab Mon Sep 17 00:00:00 2001 From: Danielle Voznyy Date: Tue, 26 Dec 2023 23:26:34 -0500 Subject: [PATCH] Add MaterialByNameSerializer, use it in SerializableItemStack --- .../serialization/MaterialByNameSerializer.kt | 24 +++++++++++++++++++ .../serialization/SerializableItemStack.kt | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/MaterialByNameSerializer.kt diff --git a/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/MaterialByNameSerializer.kt b/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/MaterialByNameSerializer.kt new file mode 100644 index 0000000..969aa4a --- /dev/null +++ b/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/MaterialByNameSerializer.kt @@ -0,0 +1,24 @@ +package com.mineinabyss.idofront.serialization + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import org.bukkit.Material + + +object MaterialByNameSerializer : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("material", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Material) { + encoder.encodeString(value.key.toString()) + } + + override fun deserialize(decoder: Decoder): Material { + val name = decoder.decodeString() + return Material.matchMaterial(name) ?: error("Material $name does not exist") + } + +} diff --git a/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/SerializableItemStack.kt b/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/SerializableItemStack.kt index faca3eb..5cc2065 100644 --- a/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/SerializableItemStack.kt +++ b/idofront-serializers/src/main/kotlin/com/mineinabyss/idofront/serialization/SerializableItemStack.kt @@ -38,7 +38,7 @@ import java.util.* */ @Serializable data class SerializableItemStack( - @EncodeDefault(NEVER) val type: Material? = null, + @EncodeDefault(NEVER) val type: @Serializable(with= MaterialByNameSerializer::class) Material? = null, @EncodeDefault(NEVER) val amount: Int? = null, @EncodeDefault(NEVER) val customModelData: Int? = null, @EncodeDefault(NEVER) val displayName: Component? = null,