Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson can't parse a string json format data in Kotlin

I'm writing an app in Kotlin. I have a raw JSON string coming from a webservice and I need to use it with Gson.

I'm doing this:

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

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

That's the 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?

like image 238
Nicola Giancecchi Avatar asked Jul 10 '17 21:07

Nicola Giancecchi


1 Answers

you should pass a java.lang.Class rather than a kotlin.reflect.KClass, for example:

val friends = gson.fromJson(response.rawResponse, JsonElement::class.java)
like image 65
holi-java Avatar answered Sep 27 '22 17:09

holi-java