adk
12/11/2020, 10:38 AM@Serializable(with= ... )
on every subclass?adk
12/11/2020, 10:46 AM@Serializable(with=TinySerializer::class)
abstract class Tiny<out T> { abstract val value: T }
data class SortCode(override val value: String) : Tiny<String>()
val sortCode = SortCode("12-34-56")
assertEquals(Json.encodeToString(sortCode), "12-34-56")
Javier
12/11/2020, 11:50 AMadk
12/11/2020, 4:44 PM@Serializable(with=...)
requires a class literal, which forces a custom serializer for every tiny type, because deserialization requires it to construct an instance of the concrete tiny type.
2. Contextual + SerializerModule, as suggested by @Javier, which requires every field the has a tiny type to be annotated with @Contextual
, plus listing the serializer in a SerializerModule and passing the module to the Json formatter. This approach does give the option of having just one generic custom serializer because we can call a method and pass parameters to customize the way it works.
Overall, I suspect option one is the least distasteful, as it keeps the boilerplate confined to the declaration of the tiny type. e.g.
@Serializable(with=SortCodeSerializer::class)
data class SortCode(override val value: String) : Tiny<String>()
object SortCodeSerializer: TinySerializer<String, SortCode>(::SortCode, serializer())
adk
12/11/2020, 4:46 PMJavier
12/11/2020, 4:47 PMJavier
12/11/2020, 4:48 PMJavier
12/11/2020, 4:48 PMadk
12/11/2020, 4:55 PMJavier
12/11/2020, 5:08 PMadk
12/11/2020, 5:13 PMadk
12/11/2020, 5:15 PMadk
12/11/2020, 5:17 PMJavier
12/11/2020, 5:27 PMadk
12/11/2020, 5:28 PM