简体   繁体   中英

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 ?

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.

实现这一目标的另一种方法是:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM