In this post under Jackson –> JSON, I will explain with example how to marshal and unmarshal a generic object.
Below is the complete main code for your reference
Main class
1 package package14;
2
3 import com.fasterxml.jackson.core.type.TypeReference;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5
6 import java.util.ArrayList;
7 import java.util.List;
8
9 public class Example14 {
10 public static void main(String[] args) throws Exception {
11 List<Integer> list = new ArrayList<>(0);
12 list.add(1);
13 list.add(2);
14 list.add(3);
15
16 ObjectMapper objectMapper = new ObjectMapper();
17 String result = objectMapper.writeValueAsString(list);
18
19 TypeReference<List<Integer>> ref = new TypeReference<List<Integer>>() { };
20 list = objectMapper.readValue(result, ref);
21 System.out.println(list);
22 }
23 }
In the above code, at line 11, I create a list named “list” of type parameter “Integer”.
From line 12 to 14, I populate it.
At line 16, I create an instance of “ObjectMapper” named “objectMapper”.
At line 17, I marshal the collection and store the output to String variable “result”.
As you know at runtime Java erases the type parameter information of generic class. So in this case also, “list” type information is erased and it is now just a list of type parameter “Object”.
To store the actual type information, we take help of “TypeReference” class.
We need to extend this class and provide the type information which we want to save.
In this case “List<Integer>”. So at line 19, we create an instance of anonymous class extending “TypeReference” class and storing that object in “ref” variable.
As you can see at line 19, when creating an instance of “TypeReference” named “ref” and I provided the type information “List<Integer>” as type parameter to “TypeReference” class.
In this way we are saving the actual type information i.e., “List<Integer>” in an “TypeReference” class instance.
At line 20, we unmarshal the value stored in “result” variable by calling “readValue” method and pass the “result” and “ref” variables as argument.
The result of this operation is a list of type “Integer”.
In this way, we marshal and unmarshal a generic object.