Using Java 8. I want to make a generic function that I can use for mapping the contents of a JSONArray
object to a certain class. The inputs to this function will be a JSONArray
and a class object that has a constructor that will turn the individual JSONObject
s inside the JSONArray
into the appropriate POJO.
I want something like this:
public static List<T> getObjectsFromJSONArray(Class T, JSONArray input) {
return IntStream.range(0, input.length())
.mapToObj(index -> (JSONObject)input.get(index))
.collect(Collectors.toList())
.forEach(jsonObj -> new T(jsonObj));
}
This doesn't compile. Perhaps because I am new to Java and am not accustomed to it, I want to make this a generic function.
One possible alternate solution is to make a class U<T>
, that extends List and acts for all intents and purposes as a List<T>
. The constructor for U
would then take the whole JSONArray then my code works with the type specified. I've seen that implementation in action before, but it seems cumbersome to me. Let me know if a new class U
is indeed the 'best practices' way to do this in Java.