Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - Deserialising JSON string - TypeReference vs TypeFactory.constructCollectionType

To deserialise JSON string to a list of class, different ways listed at StackOverflow question

Type 1 (docs link):

List<SomeClass> someClassList = mapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class)); 

Type 2 (docs link):

List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { }); 

Though both 2 types above do the job, what is the difference between these implementations ?

like image 575
Arun Avatar asked Aug 13 '12 14:08

Arun


People also ask

What is Jackson's TypeReference?

Class TypeReference<T>This generic abstract class is used for obtaining full generics type information by sub-classing; it must be converted to ResolvedType implementation (implemented by JavaType from "databind" bundle) to be used.

How do I read JSON file with ObjectMapper?

Read Object From JSON via URL ObjectMapper objectMapper = new ObjectMapper(); URL url = new URL("file:data/car. json"); Car car = objectMapper. readValue(url, Car. class);

What is the use of ObjectMapper readValue?

The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.

What is the use of Jackson ObjectMapper?

ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.


1 Answers

After constructing JavaType, both call same deserialization functionality, so the only difference is the way generic type is handled.

Second one is fully static, so type must be known in compile type, and can not vary. So it is similar to using basic Class literal.

First one is dynamic, so it can be used to construct things that vary regarding their parameterization.

Personally I prefer first alternative for all cases (it avoids creation of one more anonymous inner classes), but second one may be more readable.

like image 137
StaxMan Avatar answered Oct 02 '22 04:10

StaxMan