简体   繁体   English

使用GSON反序列化通用类型

[英]Deserializing Generic Type with GSON

I've already seen this question: 我已经看过这个问题了:

Deserializing Generic Types with GSON 使用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: 但是我的用例不同,我需要的只是将json转换为T ,而不是List<T>或类似的东西。这是我在代码中需要的:

 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. 它返回LinkedHashMap或类似的东西,但不返回T表示的类。当我将T替换为实际的类类型时,它可以工作,但对于T则不起作用。 Could someone give me some advice ? 有人可以给我一些建议吗? Thanks 谢谢

Just use Gson().fromJson(json, T.class); 只需使用Gson().fromJson(json, T.class); no TypeToken needed 无需TypeToken

I've found solution: Using just T::class.java was not enough, It gave me compilation error: 我找到了解决方案:仅使用T::class.java是不够的,它给了我编译错误:

Cannot use T as reified type parameter. 不能将T用作化类型参数。 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 之后,不会显示任何编译错误,并且代码可以在此处提供有关此主题的更多信息: 在Kotlin中实例化通用数组

and the deserialization looks like this: 反序列化看起来像这样:

 Gson().fromJson(json, T::class.java)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM