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 ?
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.
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With