toJson 和 fromJson 跨平台支持
toJson and fromJson cross platform support
我有一个用 Kotlin 编写的 android 应用程序。我有许多 classes,对于每个 class,我为这些 classes 使用 Gson's
toJson
和 fromJson
函数。例如:
class A{
fun toJson():String {
return Gson().toJson(this)
}
fun fromJson(jsonString:String):A{
return Gson().fromJson(jsonString, A::class)
}
}
我还有一个classB
:
class B{
fun toJson():String {
return Gson().toJson(this)
}
fun fromJson(jsonString:String):B{
return Gson().fromJson(jsonString, B::class)
}
}
我使用它的方式是创建一个 class 的实例,然后调用该方法(注意:我正在另一个中创建这个 class (class A
) 的实例class:
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)
}
使用上述特定于平台的实现,我无法使用 class 名称的实例调用 toJsonClassA
或 fromJsonClassA
函数。
这行不通:
val a = A()
a.toJsonClassA()
任何关于如何在 Kotlin Multiplatform 中实现 Json 序列化和反序列化的帮助或建议都将不胜感激。
回答你的问题。您需要一个多平台 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
方法。自从你有一个 class 喜欢
@Serializable
class B {}
val b = B()
kotlinx.serialization
满足您的所有需求
- 转换为
Json
、Json.stringify(B.serializer(),b)
- 解析
Json
为kotlin对象,Json.parse(B.serializer(),"{}")
我有一个用 Kotlin 编写的 android 应用程序。我有许多 classes,对于每个 class,我为这些 classes 使用 Gson's
toJson
和 fromJson
函数。例如:
class A{
fun toJson():String {
return Gson().toJson(this)
}
fun fromJson(jsonString:String):A{
return Gson().fromJson(jsonString, A::class)
}
}
我还有一个classB
:
class B{
fun toJson():String {
return Gson().toJson(this)
}
fun fromJson(jsonString:String):B{
return Gson().fromJson(jsonString, B::class)
}
}
我使用它的方式是创建一个 class 的实例,然后调用该方法(注意:我正在另一个中创建这个 class (class A
) 的实例class:
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)
}
使用上述特定于平台的实现,我无法使用 class 名称的实例调用 toJsonClassA
或 fromJsonClassA
函数。
这行不通:
val a = A()
a.toJsonClassA()
任何关于如何在 Kotlin Multiplatform 中实现 Json 序列化和反序列化的帮助或建议都将不胜感激。
回答你的问题。您需要一个多平台 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
方法。自从你有一个 class 喜欢
@Serializable
class B {}
val b = B()
kotlinx.serialization
- 转换为
Json
、Json.stringify(B.serializer(),b)
- 解析
Json
为kotlin对象,Json.parse(B.serializer(),"{}")