Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: 服务端与客户端间的序列化 #55

Merged
merged 3 commits into from
Apr 22, 2024
Merged

Conversation

xfqwdsj
Copy link
Contributor

@xfqwdsj xfqwdsj commented Apr 15, 2024

我曾经认为 kotlinx-serialization 不支持反序列化密封类,于是采用了一种不那么好的解决方案。事实上,它支持这项功能,只不过需要在序列化时指定需要序列化的类型。

@Serializable
sealed class ResponseBody {
    @Serializable
    data class Success(val token: String, val otpNeeded: Boolean = false) : ResponseBody()

    @Serializable
    data object InvalidCredential : ResponseBody()

    @Serializable
    data object Failure : ResponseBody()
}

这个密封类的 Success 数据类在 Ktor 中可以使用以下方法序列化为 ResponseBody 类型:

call.respond<ResponseBody>(ResponseBody.Success("token"))

这样一来,就有如下方法:

val body = response.body<ResponseBody>()

body is ResponseBody.Success

@xfqwdsj xfqwdsj force-pushed the refactor-serialization branch from b772f44 to 4219d1e Compare April 17, 2024 06:23
@xfqwdsj xfqwdsj force-pushed the refactor-serialization branch from 1b5fc39 to e37f540 Compare April 22, 2024 03:40
@xfqwdsj xfqwdsj merged commit 94c5ae2 into main Apr 22, 2024
@xfqwdsj xfqwdsj deleted the refactor-serialization branch April 22, 2024 03:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant