Serialize and DeSerialize Generic classes

In this post under Gson, I will show with example how to serialize and deserialize generic classes.

Below is the complete code for your reference

Main class

1  package defaultPackage;
2
3 import com.google.gson.Gson;
4 import com.google.gson.reflect.TypeToken;
5
6 import java.lang.reflect.Type;
7 import java.util.ArrayList;
8 import java.util.List;
9
10 public class GsonDemo16 {
11 public static void main(String[] args) {
12 List<String> actors = new ArrayList<>(0);
13 actors.add("John McClane");
14 actors.add("John Doe");
15 actors.add("Doe McClane");
16
17 Gson gson = new Gson();
18 Type listTypeToken = new TypeToken<List<String>>() {}.getType();
19
20 System.out.println("------------------Serialization-------------------------");
21 String result = gson.toJson(actors);
22 System.out.println(result);
23
24 actors = null;
25
26 System.out.println("----------------------DeSerialization---------------------");
27 actors = gson.fromJson(result, listTypeToken);
28 for(String actor : actors) {
29 System.out.println(actor);
30 }
31 }
32 }

In the above code, at line 12, I create an instance of generic List class and pass “String” as the type parameter.

Since List is generic class, the type parameter is erased after compilation. As a result there is no way to figure out the type parameter of List at runtime.

To fix this problem, Gson provides “TypeToken” abstract class which will store the type parameter at runtime also

At line 18, to store the type parameter information (which is String in this case), I subclass “TypeToken” abstract class and pass “List<String>” as type parameter.

At line same line, we call “getType” method on the “TypeToken” instance, which will return type information of type parameter which is “String” in this case.

At line 21, we serialize the list by calling the usual “toJson” method available on the Gson object and store the serialized version in String variable “result”.

At line 27, we deserialize the String data stored in “result” variable by calling a overloaded version of “fromJson” which takes an instance of “String”, and “Type” class as an argument.

So in our case, we are calling “fromJson” method passing the serialzed data and also the type parameter information which in this case is “String” as arguments.

In this way we can serialize and deserialize the generic classes.

Below is the output

Output

------------------Serialization-------------------------
["John McClane","John Doe","Doe McClane"]
----------------------DeSerialization---------------------
John McClane
John Doe
Doe McClane

Leave a Reply