44

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 ?

Logan Bailey
  • 7,039
  • 7
  • 36
  • 44
Arun
  • 1,729
  • 1
  • 14
  • 20
  • Can this class, `SomeClass` be made generic and have the same way a list is constructed from JSON? – kChak May 05 '21 at 05:46

2 Answers2

42

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • Can this class, `SomeClass` be made generic and have the same way a list is constructed from JSON? – kChak May 05 '21 at 05:45
  • Yes, you could have `SomeClass` and it could be used via `TypeReference` or dynamically constructed; and deserialization should work as well. – StaxMan May 06 '21 at 20:02
0

One more way you can achieve this is by :

List<SomeClass> list = Arrays.asList(mapper.readValue(jsonString, SomeClass[].class));