Jackson - Deserialising JSON string - TypeReference vs TypeFactory.constructCollectionType

a 夏天 提交于 2019-12-20 09:32:36

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/11936620/jackson-deserialising-json-string-typereference-vs-typefactory-constructcoll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!