개발/삽질
ClassCastException: com.google.gson.internal.LinkedTreeMap 에러 발생시
창이2
2023. 3. 20. 23:36
Gson으로 SharedPreference에 저장된 List를 가져와 처리를 하려할때 Type이 소거돼 제대로된 타입을 읽지 못할때
hashCode, equals 가 제대로 동작 안한다.
reified T 를 통해 런타임때 타입추론이 가능하도록 변경
inline fun <reified T> getBookmarkedImageList(
sharedPref: SharedPreferences,
key: String,
type: Type
): List<T> {
val savedStringValue = sharedPref.getString(key, "[]")
var list = emptyList<T>()
if (savedStringValue != null && savedStringValue != "[]") {
list = GsonBuilder().create().fromJson(
savedStringValue, type
)
}
return list
}