通过Class在java中的通用列表?
我有一种从服务读取 JSON 的方法,我使用 Gson 进行序列化,并使用类型参数编写了以下方法。
public T getDeserializedJSON(Class<T> aClass,String url)
{
Reader r = getJSONDataAsReader(url);
Gson gson = new Gson();
return gson.fromJson(r, aClass);
}
我正在使用 json,它只返回一个类型的数组,例如
[
{ "prop":"value" }
{ "prop":"value" }
]
我有一个映射到该对象的 java 类,我们将其称为 MyClass。然而,要使用我的方法,我需要这样做:
RestClient<ArrayList<MyClass>> restClient = new RestClient<ArrayList<MyClass>>();
ArrayList<MyClass> results = restClient.getDeserializedJSON(ArrayList<MyClass>.class, url);
但是,我无法弄清楚执行此操作的语法。仅传递 ArrayList.class 不起作用。
那么有没有办法摆脱 Class 参数或者如何获取 MyClass 的 ArrayList 的类?
I have a method for reading JSON from a service, I'm using Gson to do my serialization and have written the following method using type parameters.
public T getDeserializedJSON(Class<T> aClass,String url)
{
Reader r = getJSONDataAsReader(url);
Gson gson = new Gson();
return gson.fromJson(r, aClass);
}
I'm consuming json which returns just an array of a type e.g.
[
{ "prop":"value" }
{ "prop":"value" }
]
I have a java class which maps to this object let's call it MyClass. However to use my method I need to do this:
RestClient<ArrayList<MyClass>> restClient = new RestClient<ArrayList<MyClass>>();
ArrayList<MyClass> results = restClient.getDeserializedJSON(ArrayList<MyClass>.class, url);
However, I can't figure out the syntax to do it. Passing just ArrayList.class doesn't work.
So is there a way I can get rid of the Class parameter or how do I get the class of the ArrayList of MyClass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用 Bozho 的解决方案,或者通过使用避免创建临时数组列表:
此解决方案的唯一问题是您必须使用
@SuppressWarnings("unchecked")
抑制未检查的警告。You can use Bozho's solution, or avoid the creation of a temporary array list by using:
The only problem with this solution is that you have to suppress the unchecked warning with
@SuppressWarnings("unchecked")
.你不能。你必须使用不安全的强制转换:
You can't. You'd have to use unsafe cast:
作为后续,我在 Gson 文档中找到了这一点。
这解决了安全获取类型的问题,但 TypeToken 类是 Gson 特有的。
As a follow up to this, I found this in the Gson docs.
Which solves the problem of getting the type safely but the TypeToken class is specific to Gson.
如果您使用的是 SpringFramework,则可以使用 ParameterizedTypeReference
如下:
If you are using
SpringFramework
you could useParameterizedTypeReference
as follows:
我有一个类似的场景,但我有一个解决方法,使用数组而不是 ArrayList
这里是什么 反序列化 方法然后
您可以继续处理列表,如下所示:
I had a similar scenario but I have a workaround to use an array instead of ArrayList
And here what deserialize method does
You can then proceed with list as follows:
根据您的要求,但如果您可以使用数组,您可以提供类:
MyClass[].class
Depending on how is your requirement, but if you are ok working with array there you can provide as Class:
MyClass[].class