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     }   
复制代码

猜你喜欢

转载自blog.csdn.net/jdnicky/article/details/80225451