Bug com.google.gson.internal.LinkedTreeMap cannot be cast to XXX

public class BaseResponse<T> {
    public String status;
    public String msg;
    public int code;
    public T data;
}
Copy the code

BaseResponse

> :

val response:BaseResponse<ArrayList<Channel>> = fromJson<BaseResponse<ArrayList<Channel>>>(result)
Copy the code

Debug shows that all elements in the collection areLinkedTreeMap Direct use of packaged data is definitely problematic, as shown in the figure:

The compiler prompts an incorrect result:

LinkedTreeMap must be converted:

val toJsonTree = Gson().toJsonTree(response.data)
val testChannels: List<Channel> = Gson().fromJson<List<Channel>>(toJsonTree, object : TypeToken<List<Channel>>() {}.type)

testChannels.forEach {
   L.e("testChannels ${it.title}")
}
Copy the code

Over 🚀

Attach GsonExt

import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonParser import com.google.gson.JsonSyntaxException import org.json.JSONException import org.json.JSONObject import java.lang.reflect.Type import java.util.* /** * Title: GsonExt * * Description: com.google.gson.Gson * * @author javakam * @date 2019/12/17 10:13 */ private val sGson = createGson() private fun createGson(): Gson? { synchronized(Gson::class.java) { return sGson ? : GsonBuilder().serializeNulls().create()!! Fun <T> toJsonString(T: T): String = createGson()? .toJson(t).toString() @Throws(JSONException::class) fun toJson(obj: Any?) : JSONObject = JSONObject(createGson()? .toJson(obj) ? : "") // Extend the Java class's gson.fromjson method in kotlin // Instead of passing in T's class, inline inserts the function at the called point, Inline fun <reified T: Any> fromJson(json: String): T { return Gson().fromJson(json, T: class. Java)} / * * * * / @ Throws a json String to object (JsonSyntaxException: : class) fun < T > fromJson (json: String?, cla: Class<T>?): T = createGson()?.fromJson(json, cla)!! /** * new TypeToken<List></List><Music>>(){}.getType() */ @Throws(JsonSyntaxException::class) fun <T> fromJson(jsonStr: String? , type: Type?) : List<T> { return createGson()? .fromJson(jsonStr, type) ?: emptyList() }Copy the code