Hi folks, i have an interface ```public sealed in...
# serialization
g
Hi folks, i have an interface
Copy code
public sealed interface SharedPayload {
    public val data: JsonElement?
    public val error: ApiError?
}
and an impl
Copy code
@PublishedApi
@Serializable
internal class SharedSharedPayloadFromBuilder : SharedPayloadBuilder, SharedPayload {
    @Transient
    private var hasData = false

    @Transient
    private var hasErrors = false

    @Polymorphic
    override var data: JsonElement? = null
        private set

    override var error: ApiError? = null
        private set

    override fun data(value: JsonElement?) {
        if (hasData) {
            error("Data already provided")
        }
        data = value
        hasData = true
    }

    override fun error(value: ApiError) {
        if (hasErrors) {
            error("Error already provided")
        }
        error = value
        hasErrors = true
    }

    fun build(): SharedPayload {
        check(hasData || hasErrors) { "Data or error is required" }
        return this
    }
}
Im serializing any object into data as jsonElement, then i want to serialize the whole object as a jsonElement, yet i got this err
Copy code
Serializer for JsonPrimitive of kind STRING cannot be serialized polymorphically with class discriminator.
Anyone got any idea what im doing wrong? The test i run is this:
Copy code
@Test
fun test() {
    val payload = buildSharedPayload {
        data(ApiRequest("Hello from api request as json element"))
    }
    println(payload.data)
    val jsonElement = payload.encodeToJson()
    println(jsonElement)

    val data = SharedPayload("Hello im json element")//.encodeToJson()
    println(data.data)
}
fyi here is a sample project with this: https://github.com/GeorgePap-719/simple-springboot-kotlinx-serialization Thanks in advance for any help!
r
Please post large code blocks as snippets; they're quite disruptive to the channel otherwise. https://slack.com/help/articles/204145658-Create-or-paste-code-snippets-in-Slack
g
Oh ok, sure mb
r
As for the actual error, can you post a bit more of the stacktrace? Perhaps it's too early in the morning, but I'm trying to figure out which property that message is referring to. I'm guessing that ApiRequest is/inherits JsonElement?
Copy code
data(ApiRequest("Hello from api request as json element"))
g
My code has made a 180 turn since i posted this but yes error is about the data
I never made it to work this way so i refactored everything to make it work with generics. This error was a bit weird for me since it did not let me serialze again a json object/primtive . The Payload has a json element but i was going to serialize again the whole payload as jsonElement