My scenario:
I get a jsonArray, I want to convert this jsonArray to a List of desired type; ie List<Integer>
, List<String>
etc.
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
?
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.
Java doesn't yet provide an official way to represent generic types . As stated in the javadoc , the TypeToken has been provided in order to give the possibility to represent these types. So, the simple solution would be to use it as a parameter to the jsonArrayToJavaList method. However it will be just an indirection to the call of fromJson.
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.