Gson cannot parse json format data in Kotlin

I am writing an application in Kotlin. I have a JSON source string coming from a web service and I need to use it with Gson.

I'm doing it:

val gson = Gson()
val friends = gson.fromJson(response.rawResponse, JsonElement::class)

but the compiler cannot find the correct method overload fromJson, which is currently available ( fromJson(json: String!, typeOfT: Type!)).

What an error:

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

What am I doing wrong?

+4
source share
1 answer

you should pass java.lang.Class, not kotlin.reflect.KClass, for example:

val friends = gson.fromJson(response.rawResponse, JsonElement::class.java)
+7
source

Source: https://habr.com/ru/post/1681152/


All Articles