I have the following enum class that has a custom ...
# serialization
k
I have the following enum class that has a custom serializer
Copy code
@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.
Copy code
@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.
Copy code
@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?
Looks like adding the serializer I need to the runtime
serializerModules
works, but I don't understand why this is necessary?
Copy code
val json = Json {
      prettyPrint = true
      serializersModule = serializersModuleOf(RepresentedAreaSerializer)
    }