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
Just use Gson().fromJson(json, T.class);
no TypeToken needed
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.