我正在尝试创建解析同一密封类中的对象的机制,并基于某种类型的确定,以便能够将字符串解析为该特定类。
这是示例设置:
1)密封类:
sealed class Animal
data class Dog(
var name: String
): Animal()
data class Cat(
var color: String
): Animal()
2)解析json到该特定类的解析方法
fun parse(json: String, model: KClass<out Animal>) {
//so how to pass the type of the "model" parameter to this brackets instead of question mark?
val animal = gson.fromJson<?>(json, object : TypeToken<?>() {}.type)
//and then do something
}
所以我想我希望能够像这样使用它:
json = "" //some json
parse(json, Cat::class)
如何实现这一目标?
我现在能找到的唯一方法是这样的:
fun parse(json: String, model: KClass<out Animal>) {
when (model) {
Cat::class -> {
val cat = gson.fromJson<Cat>(json, object : TypeToken<Cat>() {}.type)
//and then do something
}
Dog::class -> {
val dog = gson.fromJson<Dog>(json, object : TypeToken<Dog>() {}.type)
//and then do something
}
}
}
但是还有更好的方法吗?
最佳答案
您可以使用具体化通用参数( Kotlin documentation )。
然后可以像普通类一样使用类型参数:
inline fun <reified T> parse(json: String) {
val animal = gson.fromJson<T>(json, object : TypeToken<T>() {}.type)
//do somehing with the result
when(animal) {
is Dog -> ...
is Cat -> ...
}
}
//Call parse function
parse<Cat>(json)
关于java - 如何判断类的类型并通过fromJson方法括号传递给gson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52636540/