我有一个用Kotlin写的android应用程序。我有许多类,对于每个类,我为这些类使用了Gson's toJson和fromJson函数。例如:
class A{
fun toJson():String {
return Gson().toJson(this)
}
fun fromJson(jsonString:String):A{
return Gson().fromJson(jsonString, A::class)
}
}我还有一班B
class B{
fun toJson():String {
return Gson().toJson(this)
}
fun fromJson(jsonString:String):B{
return Gson().fromJson(jsonString, B::class)
}
}我使用它的方式是创建类的一个实例,然后调用方法(注意:我在另一个类中创建这个类的实例(class A):
val a = A()
a.toJson()但我现在正试图将其转换为kotlin多平台项目,但不确定如何处理kotlin多平台中的to和from json转换。
我尝试以这样的方式创建expect函数:
expect fun toJsonClassA():String
expect fun fromJsonClassA(jsonString: String): A
class A{
}然后将它们实现为这样的实际实现:
actual fun toJsonClassA(): String {
return Gson().toJson(A::class.java)
}对于上面平台特定的实现,我不能用类名的实例调用toJsonClassA或fromJsonClassA函数。
这不管用:
val a = A()
a.toJsonClassA()任何关于我如何在Kotlin多平台上实现Json序列化和反序列化的帮助或建议都将受到高度赞赏。
发布于 2020-08-11 20:28:06
回答你的问题。您需要一个多平台json序列化程序(而不是GSon,因为它只适用于jvm ),目前我只知道kotlinx.serialization。使用它,您的代码应该如下所示
@Serializable
class A {
fun toJson() = Json.stringify(A.serializer(),this)
companion object {
fun fromJson(json: String) = Json.parse(A.serializer(),json)
}
}虽然这样做有效,但您不需要toJson和fromJson方法。从什么时候起你就有了一门课
@Serializable
class B {}
val b = B()使用kotlinx.serialization所需的一切
Json.stringify(B.serializer(),b)
Json,将Json解析为kotlin对象,Json.parse(B.serializer(),"{}")https://stackoverflow.com/questions/63353642
复制相似问题