封装一个转指定实体类 list 的方法,有如下两种
public static <T> List<T> parseList(String jsonString, Class<T> elementClazz) throws Exception {
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<T>> typeReference = new TypeReference<List<T>>() {};
return mapper.readValue(jsonString, typeReference);
}
public static <T> List<T> parseList(String jsonString, TypeReference<List<T>> typeReference) throws Exception {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jsonString, typeReference);
}
public static void main(String[] args) throws Exception {
String jsonListStr = "[{\"username\":\"pure1\",\"phone\":\"18xxx\"},{\"username\":\"pure2\",\"phone\":\"19xxx\"}]";
List<User> userList1 = parseList(jsonListStr, User.class);
List<User> userList2 = parseList(jsonListStr, new TypeReference<List<User>>(){});
}
两个转完的 list 里,第一个 list 里的对象在断点里看实际上是个LinkedHashMap ,是无法正常调用实体类的 get 方法的。第二个 list 里的对象就是真正的User。所以我分别去看了两个方法的 typeReference 对象,第一个方法的 typeReference 对象里的_type 值为“java.util.List<T>”,第二个方法里的 typeReference 对象里的_type 值为“java.util.List<xxx.xxx.entity.User>”。虽然第二个方法可以正常使用,但是封装肯定是为了简便,以TypeReference<List<T>> typeReference作为入参感觉很奇怪,我底层了解的不多,我的认知里在入参的时候 new 一个 TypeReference 和在方法里 new 一个 TypeReference 应该是一样的才对。希望有大牛帮我解惑,或者是不是我第一个方法的代码写的有问题。
在此先谢谢各位了!!!
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.