Reputation: 2341
I've already seen this question:
Deserializing Generic Types with GSON
but my use case is different, what I need is just convert json to T
, and not List<T>
or similar..
Here is what i need in code:
val type: Type = object : TypeToken<T>() {}.type
and then
Gson().fromJson<T>(json, type)
But it's not working. It returns LinkedHashMap or something like that, but not the class represented by T. When I replace T with actual class type, it works, but with T it's not working. Could someone give me some advice ? Thanks
Upvotes: 1
Views: 1700
Reputation: 2341
I've found solution:
Using just T::class.java
was not enough, It gave me compilation error:
Cannot use T as reified type parameter. Use class instead
So I had to find solution how to fix it. What I had to do was change name of the function from this:
fun <T> myFunction
to this:
inline fun <reified T> myFunction
after that, no compilation error is shown, and code works more info about this topic is here : Instantiating generic array in Kotlin
and the deserialization looks like this:
Gson().fromJson(json, T::class.java)
Upvotes: 3