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.
Tis justjava.lang.Object(respectively Kotlin'sAny, I assume). Gson deserializesObjectby default to aMap. If you can change yourJsonFeatureFlagclass to include the runtime class ofT, then you can directly pass that class to theGson.fromJsoncall.