码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2017-02-07 23:29:39      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:cep   序列化   cti   字符串   shm   nal   read   ntc   html   

转:http://www.cnblogs.com/quanyongan/archive/2013/04/16/3024993.html

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);

    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);   
    }

 

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

标签:cep   序列化   cti   字符串   shm   nal   read   ntc   html   

原文地址:http://www.cnblogs.com/peach/p/6376142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!