Gson的泛型类型的Java反序列化 [英] Java deserialization of generic type with Gson
本文介绍了Gson的泛型类型的Java反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图反序列化一些泛型类型。它很好,但我想将这段代码换成一个方法。
输入listType = new TypeToken< TestResult< ;为MyObject>>(){}的getType();
TestResult< MyObject> result = new Gson()。fromJson(json,listType);
如何做到这一点,证明有关该类型的信息?
解决方案
你不能。
泛型的类型无法在运行时确定。
一个简单的解决方法是将方法添加到 MyObject
返回结果类型(就像代码示例的第一行)。
I'm trying to deserialize some generic type. It works nice, but I would like to swap this piece of code out to a method.
Type listType = new TypeToken<TestResult<MyObject>>(){}.getType();
TestResult<MyObject> result = new Gson().fromJson(json, listType);
How to I do this, proving information about the type?
解决方案
You can't. The type of a generics can't be determinted during runtime.
An easy workaround would be to add a method to MyObject
to return the resulting Type (like the first line of your code sample).
这篇关于Gson的泛型类型的Java反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文