Custom serializer for third party enum does not propagate across packages
Describe the bug
Custom serializer for third party enum does not propagate across packages
To Reproduce
I have package A, with a third-party enum that is not serializable, and I want to serialize it by enum value, so I wrote a custom serializer for it in package A.
package com.third.party
enum class ThirdPartyEnum(val name: String) {
TEST_1("test1")
TEST_2("test2")
}
package com.a
import com.third.party.ThirdPartyEnum
object ThirdPartyEnumSerializer : KSerializer<ThirdPartyEnum> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("ThirdPartyEnum", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: ThirdPartyEnum) {
return encoder.encodeString(value.name)
}
override fun deserialize(decoder: Decoder): ThirdPartyEnum {
return fromShortName(decoder.decodeString())!!
}
}
@Serializable
data class TestObject(
@Serializable(with = ThirdPartyEnumSerializer::class)
val enumEntry1: ThirdPartyEnum,
@Serializable(with = ThirdPartyEnumSerializer::class)
val enumEntry2: ThirdPartyEnum
)
fun main() {
val obj = TestObject(
enumEntry1 = ThirdPartyEnum.TEST_1,
enumEntry2 = ThirdPartyEnum.TEST_2
)
println(Json.encodeToString(TestObject.serializer()), obj)
// Prints "{"enumEntry1": "test1", "enumEntry2": "test2"}"
}
I then implement package A in package B and try to encode TestObject as string
implementation(project(":package-a")
implementation("com.third.party:x.x.x")
val obj = TestObject(
enumEntry1 = ThirdPartyEnum.TEST_1,
enumEntry2 = ThirdPartyEnum.TEST_2
)
println(Json.encodeToString(TestObject.serializer()), obj)
// Prints "{"enumEntry1": "TEST_1", "enumEntry2": "TEST_2"}"
Expected behavior
Json.encodeToString in package B should produce the same result as package A
Environment
- Kotlin version: 1.9.10
- Library version: 1.6.0
- Kotlin platforms: JVM
- Gradle version: 7.6.3
Custom serializers are compiled into the code of TestObject.serializer(), so they shouldn't be affected whether they're used from the same module or as a binary dependency. Can you please re-check that you're using a proper dependency version and that it is not affected by e.g. incremental compilation or Gradle cache?