kevin.cianfarini
09/28/2021, 12:44 PM@Serializable(with = RepresentedAreaSerializer::class)
enum class RepresentedArea(override val value: String) : StringEnum {
Alaska("AK"),
Alabama("AL"),
AmericanSamoa("AS")
...
}
object RepresentedAreaSerializer : StringEnumSerializer(RepresentedArea.values())
abstract class StringEnumSerializer<T>(
enumValues: Array<out T>,
) : KSerializer<T> where T : StringEnum, T : Enum<T> {
private val enumMap = enumValues.associateBy { it.value }
override val descriptor get() = PrimitiveSerialDescriptor("StringEnumSerializer", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: T) = encoder.encodeString(value.value)
override fun deserialize(decoder: Decoder): T = checkNotNull(enumMap[decoder.decodeString()])
}
When I try to serialize this value with the following method, I get an error that Serializer for class 'RepresentedArea' is not found.
@Test fun foo() {
val json = Json { prettyPrint = true}
assertEquals("VA", json.encodeToString(RepresentedArea.Virginia)) // runtime error
}
The strange bit is that I can serialize it as a part of other object structures. For example, the following works for both serializing and deserializing.
@Serializable class GetLegislatorsByAddressRequest(
val streetAddress: String,
val city: String,
val state: RepresentedArea,
val postalCode: String,
)
I'm a bit stuck on this error. Does anyone have any ideas what I'm doing wrong?kevin.cianfarini
09/28/2021, 1:06 PMserializerModules
works, but I don't understand why this is necessary?
val json = Json {
prettyPrint = true
serializersModule = serializersModuleOf(RepresentedAreaSerializer)
}