https://kotlinlang.org logo
#ktor
Title
# ktor
r

Rescribet

08/02/2021, 7:55 AM
Is there a reason why
io.ktor.http.URL
isn’t
@Serializable
? Seems like a good way to avoid

primitive obsession

and a quick win to get basic validation:
Copy code
@Serializable
data class Person(
    val name: String,
    val friends: String,
)
val p = Person("Abbey", "<http://ex.com/abbey/friends>")
Json.encodeToString(p) // { "name": "Abbey", "friends": "<http://ex.com/abbey/friends>" }

val err = """
	{ "name": "Abbey", "friends": "abbey/friends" }
"""
Json.decodeFromString<Person>(err) // MalformedUrlException : SerializationException
d

Dominaezzz

08/02/2021, 7:57 AM
You can always add a simple custom serializer.
I don't think ktor-core wants to depend on
kotlinx.serialization
.
r

Rescribet

08/02/2021, 7:57 AM
That would work. I didn’t know that’s an option for external classes
d

Dominaezzz

08/02/2021, 8:05 AM
Now you know. It would look something like this.
Copy code
@Serializable
data class Person(
    val name: String,
    val friends: @Serializable(MyCustomSerializer::class) Url,
)
r

Rescribet

08/02/2021, 8:07 AM
That was quite trivial:
Copy code
object UrlSerializer : KSerializer<Url> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Url", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: Url) = encoder.encodeString(value.toString())

    override fun deserialize(decoder: Decoder): Url = Url(decoder.decodeString())
}
🎉 1
👍 3
👍🏼 1
2 Views