如何(DE)序列化生成数据类的实例

发布于 2025-02-10 02:40:38 字数 400 浏览 1 评论 0原文

我需要(de)serialize word&从JSON序列化的某些数据类 es es是由Gradle插件生成的。通常,我只会使用诸如moshi或kotlinx.Serialization之类的库,然后将适当的注释添加到我要序列化的类中是一个问题。

我想避免手动将生成的数据类的所有字段映射到我可以(DE)序列化或为所有这些Data Class < /code>因此,我想知道是否还有另一种方法可以告诉例如kotlinx.serialization class是@serializable而无需直接将注释放在班级本身。

或者,是否有一种更好的方法可以转换到字符串的实例的实例?

I need to (de)serialize to and from JSON some of the data classes that are generated by a Gradle plugin. Normally I would just use a library like Moshi or kotlinx.serialization and add the proper annotation to the class I want to serialize but, since this data classes are autogenerated, this is a problem.

I would like to avoid manually to map all the fields of the generated data class to some other class that I can (de)serialize, or to write a custom adapter for all these data class so, I was wondering if there is another way to tell, for example, kotlinx.serialization that a class is @Serializable without having to put the annotation directly on top of the class itself.

Or, alternatively, is there a better way to convert to and from a string an instance of a generated data class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秉烛思 2025-02-17 02:40:38

kotlinx.Serialization支持为第三方类生成序列化。我们需要在@serializer中使用forclass参数,例如:

data class MyData(val data: String)

@Serializer(forClass = MyData::class)
object MyDataSerializer

fun main() {
    val data = MyData("foo")
    println(Json.encodeToString(MyDataSerializer, data))
}

您可以在官方文档中阅读更多: https://github.com/github.com/kotlin/kotlinx。 serialization/blob/master/doc/serializers.md#deriving-external-serializer-for-hother-kotlin-class-class-pershiormentiment

kotlinx.serialization supports generating serializers for 3rd party classes. We need to use forClass parameter in @Serializer, for example:

data class MyData(val data: String)

@Serializer(forClass = MyData::class)
object MyDataSerializer

fun main() {
    val data = MyData("foo")
    println(Json.encodeToString(MyDataSerializer, data))
}

You can read more in the official documentation: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#deriving-external-serializer-for-another-kotlin-class-experimental

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文