KyoriPowered / adventure

A user-interface library, formerly known as text, for Minecraft: Java Edition
https://docs.advntr.dev/
MIT License
706 stars 107 forks source link

Gson deserialize not working #963

Closed Derp33 closed 1 year ago

Derp33 commented 1 year ago

Serializing and deserializing with gson results in the literal json string becoming the content

image

zml2008 commented 1 year ago

no it doesn't, show what you're actually doing

Derp33 commented 1 year ago
package algrim.mc.petcrate

import com.google.gson.*
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer
import org.bukkit.entity.LivingEntity
import java.lang.reflect.Type

class EntityData(val type: String, val health: Double, val name: Component?) {
    companion object {
        private val gson: Gson
        init {
            val gsonBuilder = GsonComponentSerializer.gson().populator().apply(GsonBuilder())
            gsonBuilder.registerTypeAdapter(LivingEntity::class.java, PetEntityDataSerializer())
            gson = gsonBuilder.create()
        }

        fun fromJson(json: String): EntityData {
            return gson.fromJson(json, EntityData::class.java)
        }

        fun toJson(entity: LivingEntity): String {
            return gson.toJson(entity, LivingEntity::class.java)
        }
    }
}

class PetEntityDataSerializer: JsonSerializer<LivingEntity> {
    override fun serialize(src: LivingEntity, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
        val json = JsonObject()

        json.addProperty("type", src.type.name)
        json.addProperty("health", src.health)

        src.customName()?.let { json.add("name", context.serialize(it)) }

        return json
    }
}

(Edited to fix the non issue 😂)

zml2008 commented 1 year ago

your serializer is for a LivingEntity but you're registering it under EntityData

Derp33 commented 1 year ago

Don't see why that'd be a problem but ok

Edit: I'd like to clarify. Gson allows you to serialize one type as another. The laughing emoji doesn't change that.