[英]How can I pass the type for the List I want return?
My scenario: 我的情况:
I get a jsonArray, I want to convert this jsonArray to a List of desired type; 我得到一个jsonArray,我想将此jsonArray转换为所需类型的列表。 ie
List<Integer>
, List<String>
etc. 即
List<Integer>
, List<String>
等。
Suppose I have the following method: 假设我有以下方法:
public static List jsonArrayToJavaList(JsonArray jsonArray, TYPE TYPE) {
return new Gson().fromJson(jsonArray, new TypeToken<List<TYPE>>() {}.getType());
}
How do I pass in the TYPE
? 如何传递
TYPE
?
I want to do this because this method could be used by other people and I don't want to duplicate this code for each type of list I want... 我想要这样做是因为其他人可以使用此方法,并且我不想为我想要的每种列表类型重复此代码...
I also tried: 我也尝试过:
public static List jsonArrayToJavaList(JsonArray jsonArray, final Class c) {
return new Gson().fromJson(jsonArray, new TypeToken<List<c>>() {}.getType());
}
I see the error saying unknown class c. 我看到错误提示未知的c类。
Java doesn't yet provide an official way to represent generic types . Java尚未提供表示通用类型的正式方法 。 As stated in the javadoc , the TypeToken has been provided in order to give the possibility to represent these types.
如javadoc中所述,提供了TypeToken以便表示这些类型。 So, the simple solution would be to use it as a parameter to the jsonArrayToJavaList method.
因此,简单的解决方案是将其用作jsonArrayToJavaList方法的参数。 However it will be just an indirection to the call of fromJson.
但是,这只是对fromJson调用的间接调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.