【发布时间】:2022-01-05 06:46:18
【问题描述】:
我正在关注ROOM tutorial and at some point 我们需要为 ROOM 创建类型转换器。 GSON 被用于解析 JSON。
为了实现这一点,我们首先创建了这个通用接口,它包含 2 个函数,用于从 JSON 字符串中获取对象或将对象解析为 JSON 字符串。如果您决定切换到不同的库来解析 JSON 字符串,则需要这样做。
interface JsonParser {
//takes the actual JSON String and return an object of our type
fun <T> fromJson(json: String, type: Type): T?
//takes our object and return JSON String
fun <T> toJson(obj: T, type: Type): String?
}
下一步是创建使用 GSON 的上述接口的实现。
//JsonParser implementation
class GsonParser (private val gson: Gson):JsonParser {
override fun <T> fromJson(json: String, type: Type): T? {
return gson.fromJson(json,type)
}
override fun <T> toJson(obj: T, type: Type): String? {
return gson.toJson(obj,type)
}
}
就我而言,我希望使用 Moshi 做同样的事情。不幸的是,Moshi 没有 toJson() 或 fromJson() 方法。
已尝试寻找与 GSON 的 toJson() 和 fromJson() 等效的 Moshi 方法,但我什么也没得到。我该怎么办?
【问题讨论】:
-
JsonAdapter有fromJson()和toJson()。对于 Java 和 Kotlin,它们显示在 the first examples of the project README 中。您需要为您的数据类型创建一个JsonAdapter。