I run the following code snippet:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class JsonMapper {
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static <T> String toJson(final T object) throws JsonProcessingException {
return OBJECT_MAPPER.writeValueAsString(object);
}
public static <T> T fromJson(final String json, final Class<T> clazz) throws IOException {
return OBJECT_MAPPER.readValue(json, clazz);
}
public static <T> T fromJson(final String json, final TypeReference<T> type) throws IOException {
return OBJECT_MAPPER.readValue(json, type);
}
public static void main(String args[]) throws IOException {
String json = "[1,2,3]";
// TEST1: initialize TypeReference with type ArrayList
List<Integer> expected = JsonMapper.fromJson(json, new TypeReference<ArrayList<Integer>>(){});
System.out.println(expected.getClass().getName());
// TEST2: initialize TypeReference with type List
expected = JsonMapper.fromJson(json, new TypeReference<List<Integer>>(){});
System.out.println(expected.getClass().getName());
// TEST3: initialize TypeReference with type LinkedList
expected = JsonMapper.fromJson(json, new TypeReference<LinkedList<Integer>>(){});
System.out.println(expected.getClass().getName());
}
}
the output is:
java.util.ArrayList
java.util.ArrayList
java.util.LinkedList
The type of variable expected
is ArrayList
when I initialize TypeReference
with type ArrayList
or List
, but it becomes LinkedList
if I initialize TypeReference
with type LinkedList
. So, does jackson deserialize a string list to ArrayList
in default?