google gson LinkedTreeMap class cast to myclass

后端 未结 5 809
时光取名叫无心
时光取名叫无心 2020-11-29 05:01

I knew this question has been asked before. Due to my novice skill in java and android. I can\'t resolve this issue for more than a week.

One of my friend and i dev

5条回答
  •  抹茶落季
    2020-11-29 05:33

    EngineSense's answer is correct.
    However, if you still want to use generics and don't want to pass in the concrete class type as a parameter here's an example of a workaround in Kotlin.
    (Note that inline methods with reified type params cannot be called from Java).

    May not be the most efficient way to get things done but it does work.


    The following is in GsonUtil.kt

    inline fun  fromJson(json: String): T? {
        return gson.fromJson(json, object : TypeToken() {}.type)
    }
    
    fun  mapToObject(map: Map?, type: Class): T? {
        if (map == null) return null
    
        val json = gson.toJson(map)
        return gson.fromJson(json, type)
    }
    

    Method that retrieves a lightweight list of generic objects.

    inline fun  getGenericList(): List {
        val json = ...
    
        //Must use map here because the result is a list of LinkedTreeMaps
        val list: ArrayList>? = GsonUtil.fromJson(json)
        //handle type erasure
        val result = list?.mapNotNull {
            GsonUtil.mapToObject(it, T::class.java)
        }
    
        return  result ?: listOf()
    }
    

提交回复
热议问题