Hi I have this code in Kotlin Android I try to parse JSON string to data clas, but the data is unknown, I mean the data class is genric type T
class JsonFeatureFlag<T>(
key: String,
@StringRes nameResId: Int,
category: DevOptionCategory,
val defaultValue: T
): FeatureFlagV2<T>(key, nameResId, category) {
.....
override fun getValue(): T {
val json = FirebaseRemoteConfig.getInstance().getString(key)
return try {
Gson().fromJson(json, object: TypeToken<T>(){}.type)
} catch (e: Exception) {
reportInvalidJson(json)
defaultValue
}
}
....
}
And I'm getting this error: java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to X
While I understand that TypeToken should be used for generic, something isn't working.
To solve this problem I provide a class name ie className: Class Although I used genric, when somebody wants to use my API and call getValue the type is known, and he can provide the class name to the get value method.
class JsonFeatureFlag<T>(
key: String,
@StringRes nameResId: Int,
category: DevOptionCategory,
val defaultValue: T
): FeatureFlagV2<T>(key, nameResId, category) {
fun getValue(className: Class<T>): T {
val json = FirebaseRemoteConfig.getInstance().getString(key)
return try {
Gson().fromJson(json, className)
} catch (e: Exception) {
reportInvalidJson(json)
defaultValue
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.