java的Jackson将json字符串转换成泛型List

2025-05-29 0 61

Jackson,我感觉是在Java与Json之间相互转换的最快速的框架,当然Google的Gson也很不错,但是参照网上有人的性能测试,看起来还是Jackson比较快一点

Jackson处理一般的JavaBean和Json之间的转换只要使用ObjectMapper 对象的readValue和writeValueAsString两个方法就能实现。但是如果要转换复杂类型Collection如 List<YourBean>,那么就需要先反序列化复杂类型 为泛型的Collection Type。

如果是ArrayList<YourBean>那么使用ObjectMapper 的getTypeFactory().constructParametricType(collectionClass, elementClasses);

如果是HashMap<String,YourBean>那么 ObjectMapper 的getTypeFactory().constructParametricType(HashMap.class,String.class, YourBean.class);

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
public final ObjectMapper mapper = new ObjectMapper();

public static void main(String[] args) throws Exception{

JavaType javaType = getCollectionType(ArrayList.class, YourBean.class);

List<YourBean> lst = (List<YourBean>)mapper.readValue(jsonString, javaType);

}

/**

* 获取泛型的Collection Type

* @param collectionClass 泛型的Collection

* @param elementClasses 元素类

* @return JavaType Java类型

* @since 1.0

*/

public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {

return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://www.cnblogs.com/peach/p/6376142.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java的Jackson将json字符串转换成泛型List https://www.kuaiidc.com/119163.html

相关文章

发表评论
暂无评论