1. Overview
In this tutorial, we’ll discuss converting a JSON array into an equivalent java.util.List object. Gson is a Java library by Google that helps convert JSON strings to Java objects and vice versa.
The Gson class in this library has the method fromJson() that takes in two arguments, the first argument is JSON String and the second argument is of type java.lang.reflect.Type. The method converts the JSON String to an equivalent Java object of type represented by its second argument.
We’ll come up with a generic method, say convertJsonArrayToListOfAnyType(String jsonArray, T elementType), that can convert the JSON array into List<T>, where T is the type of elements in the List.
Let’s understand more about this.
2. Problem Description
Let’s assume we have two JSON arrays, one for Student and one for School:
final String jsonArrayOfStudents =
"["
+ "{\"name\":\"John\", \"grade\":\"1\"}, "
+ "{\"name\":\"Tom\", \"grade\":\"2\"}, "
+ "{\"name\":\"Ram\", \"grade\":\"3\"}, "
+ "{\"name\":\"Sara\", \"grade\":\"1\"}"
+ "]";
final String jsonArrayOfSchools =
"["
+ "{\"name\":\"St. John\", \"city\":\"Chicago City\"}, "
+ "{\"name\":\"St. Tom\", \"city\":\"New York City\"}, "
+ "{\"name\":\"St. Ram\", \"city\":\"Mumbai\"}, "
+ "{\"name\":\"St. Sara\", \"city\":\"Budapest\"}"
+ "]";
Normally, we can use the Gson class to convert the arrays into List objects:
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingTypeToken() {
Gson gson = new Gson();
TypeToken<List<Student>> typeTokenForListOfStudents = new TypeToken<List<Student>>(){};
TypeToken<List<School>> typeTokenForListOfSchools = new TypeToken<List<School>>(){};
List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, typeTokenForListOfStudents.getType());
List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, typeTokenForListOfSchools.getType());
assertAll(
() -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
() -> schoolLst.forEach(e -> assertTrue(e instanceof School))
);
}
We created the TypeToken objects for List<Student> and List<School>. Finally, using the TypeToken objects, we got the Type objects and then converted the JSON arrays into List<Student> and List<School>.
To promote reuse, let’s try creating a generic class with a method that can take the element type in the List and return the Type object:
class ListWithDynamicTypeElement<T> {
Type getType() {
TypeToken<List<T>> typeToken = new TypeToken<List<T>>(){};
return typeToken.getType();
}
}
We’re instantiating a generic TypeToken<List<T>> for a given element type T. Then we’re returning the corresponding Type object. The list element type is available only at runtime.
Let’s see the method in action:
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingTypeTokenFails() {
Gson gson = new Gson();
List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, new ListWithDynamicTypeElement<Student>().getType());
assertFalse(studentsLst.get(0) instanceof Student);
assertThrows(ClassCastException.class, () -> studentsLst.forEach(e -> assertTrue(e instanceof Student)));
}
While the method compiles, it fails in runtime and raises a ClassCastException when we try to iterate over studentLst. Also, we see that the elements in the list are not of type Student.
3. Solution Using getParameterized() in TypeToken
In the Gson 2.10 version, the getParamterized() method was introduced in the class TypeToken. This enabled developers to handle scenarios where the type information of the list elements is not available during the compile time.
Let’s see how this new method helps return the Type information of parameterized classes:
Type getGenericTypeForListFromTypeTokenUsingGetParameterized(Class elementClass) {
return TypeToken.getParameterized(List.class, elementClass).getType();
}
The method getParamterized(), when called during runtime, would return the actual type of the List object along with its element type. Further, this would help the Gson class to convert the JSON array to the exact List object with the correct type information of its elements.
Let’s see the method in action:
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingGetParameterized() {
Gson gson = new Gson();
List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, getGenericTypeForListFromTypeTokenUsingGetParameterized(Student.class));
List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, getGenericTypeForListFromTypeTokenUsingGetParameterized(School.class));
assertAll(
() -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
() -> schoolLst.forEach(e -> assertTrue(e instanceof School))
);
}
We used the method getGenericTypeForListFromTypeTokenUsingGetParameterized() to get the Type information of List<Student> and List<School>. Finally, using the method fromJson() we converted the JSON arrays successfully to their respective Java List objects.
4. Solution Using JsonArray
The Gson library has a JsonArray class to represent a JSON array. We’ll use it for converting the JSON array into the List object:
<T> List<T> createListFromJsonArray(String jsonArray, Type elementType) {
Gson gson = new Gson();
List<T> list = new ArrayList<>();
JsonArray array = gson.fromJson(jsonArray, JsonArray.class);
for(JsonElement element : array) {
T item = gson.fromJson(element, elementType);
list.add(item);
}
return list;
}
First, we’re converting the JSON array string into the JsonArray object using the usual fromJson() method in the Gson class. Then, we convert each JsonElement element in the JsonArray object to the target Type defined by the second argument elementType in the createListFromJsonArray() method.
Each of these converted elements is put into a List and then finally returned at the end.
Now, let’s see the method in action:
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingJsonArray() {
List<Student> studentsLst = createListFromJsonArray(jsonArrayOfStudents, Student.class);
List<School> schoolLst = createListFromJsonArray(jsonArrayOfSchools, School.class);
assertAll(
() -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
() -> schoolLst.forEach(e -> assertTrue(e instanceof School))
);
}
We used the method createListFromJsonArray() to successfully convert both the JSON arrays of students and schools to List<Student> and List<School>.
5. Solution Using TypeToken From Guava
Similar to the TypeToken class in the Gson library, the TypeToken class in Guava also enables capturing generic types at runtime. Otherwise, this is not possible due to type erasure in Java.
Let’s see an implementation using the Guava TypeToken class:
<T> Type getTypeForListUsingTypeTokenFromGuava(Class<T> type) {
return new com.google.common.reflect.TypeToken<List<T>>() {}
.where(new TypeParameter<T>() {}, type)
.getType();
}
The method where() returns a TypeToken object by replacing the type parameter with the class in the variable type.
Finally, we can look at it in action:
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingTypeTokenFromGuava() {
Gson gson = new Gson();
List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, getTypeForListUsingTypeTokenFromGuava(Student.class));
List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, getTypeForListUsingTypeTokenFromGuava(School.class));
assertAll(
() -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
() -> schoolLst.forEach(e -> assertTrue(e instanceof School))
);
}
Again, we used the method fromJson() to convert the JSON array to the respective List objects. However, we got the Type object with the help of the Guava library in the method getTypeForListUsingTypeTokenFromGuava().
6. Solution Using ParameterizedType of Java Reflection API
ParameterizedType is an interface that is part of the Java reflection API. It helps represent parameterized types such as Collection<String>.
Let’s implement ParamterizedType to represent any class that has parameterized types:
public class ParameterizedTypeImpl implements ParameterizedType {
private final Class<?> rawType;
private final Type[] actualTypeArguments;
private ParameterizedTypeImpl(Class<?> rawType, Type[] actualTypeArguments) {
this.rawType = rawType;
this.actualTypeArguments = actualTypeArguments;
}
public static ParameterizedType make(Class<?> rawType, Type ... actualTypeArguments) {
return new ParameterizedTypeImpl(rawType, actualTypeArguments);
}
@Override
public Type[] getActualTypeArguments() {
return actualTypeArguments;
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public Type getOwnerType() {
return null;
}
}
The variable actualTypeArguments would store the class information of the type argument in the generic class, while rawType represents the generic class. The make() method returns the Type object of the parameterized class.
Finally, let’s see it in action:
@Test
void givenJsonArray_whenListElementTypeDynamic_thenConvertToJavaListUsingParameterizedType() {
Gson gson = new Gson();
List<Student> studentsLst = gson.fromJson(jsonArrayOfStudents, ParameterizedTypeImpl.make(List.class, Student.class));
List<School> schoolLst = gson.fromJson(jsonArrayOfSchools, ParameterizedTypeImpl.make(List.class, School.class));
assertAll(
() -> studentsLst.forEach(e -> assertTrue(e instanceof Student)),
() -> schoolLst.forEach(e -> assertTrue(e instanceof School))
);
}
We used the make() method to get the Type information of the parameterized List class and successfully converted the JSON arrays to their respective List object forms.
7. Conclusion
In this article, we discussed four different ways of getting the Type information of a List<T> object during runtime. Finally, we used the Type object for converting the JSON array to a List object using the fromJson() method in the Gson library.
Since, ultimately, it is the fromJson() method that gets invoked, the performance of all these methods is close to each other. However, the TypeToken.getParamterized() method is the most succinct, so we recommend using it.
As usual, the code used is available over on GitHub.