Skip to content

Commit

Permalink
Add MaterialByNameSerializer, use it in SerializableItemStack
Browse files Browse the repository at this point in the history
  • Loading branch information
0ffz committed Dec 27, 2023
1 parent cde108b commit e95ab41
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -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<Material> {
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")
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit e95ab41

Please sign in to comment.