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


    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     public final ObjectMapper mapper = new ObjectMapper(); 
 2      
 3     public static void main(String[] args) throws Exception{  
 4         JavaType javaType = getCollectionType(ArrayList.class, YourBean.class); 
 5         List<YourBean> lst =  (List<YourBean>)mapper.readValue(jsonString, javaType); 
 6     }   
 7        /**   
 8         * 获取泛型的Collection Type  
 9         * @param collectionClass 泛型的Collection   
10         * @param elementClasses 元素类   
11         * @return JavaType Java类型   
12         * @since 1.0   
13         */   
14     public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   
15         return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);   
16     }   

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM