我在Kotlin写了一个应用程序。我有一个来自Web服务的原始JSON字符串,我需要将它与Gson一起使用。
我这样做:
val gson = Gson()
val friends = gson.fromJson(response.rawResponse, JsonElement::class)
但是编译器无法找到正确的fromJson
方法重载,而是当前可用的(fromJson(json: String!, typeOfT: Type!)
)。
那是错误:
Error:(65, 50) None of the following functions can be called with the arguments supplied:
public open fun <T : Any!> fromJson(json: JsonElement!, classOfT: Class<JsonElement!>!): JsonElement! defined in com.google.gson.Gson
public open fun <T : Any!> fromJson(json: JsonElement!, typeOfT: Type!): JsonElement! defined in com.google.gson.Gson
public open fun <T : Any!> fromJson(reader: JsonReader!, typeOfT: Type!): JsonElement! defined in com.google.gson.Gson
public open fun <T : Any!> fromJson(json: Reader!, classOfT: Class<JsonElement!>!): JsonElement! defined in com.google.gson.Gson
public open fun <T : Any!> fromJson(json: Reader!, typeOfT: Type!): JsonElement! defined in com.google.gson.Gson
public open fun <T : Any!> fromJson(json: String!, classOfT: Class<JsonElement!>!): JsonElement! defined in com.google.gson.Gson
public open fun <T : Any!> fromJson(json: String!, typeOfT: Type!): JsonElement! defined in com.google.gson.Gson
我做错了什么?
答案 0 :(得分:8)
您应该传递java.lang.Class
而不是kotlin.reflect.KClass
,例如:
val friends = gson.fromJson(response.rawResponse, JsonElement::class.java)