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     }   
複製代碼

 





其他相關的:

[java] view plain copy
  1. JavaType javaType = TypeFactory.defaultInstance()  
  2.     constructParametrizedType(Page.class,Page.class, CustomerDTO.class);  
  3. Page<CustomerDTO> list = JsonUtil.om().readValue(res, javaType);  

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. public class JsonUtil {  
  2.     /** 
  3.      * 返回mapper,忽略未知參數、使用long解析時間 
  4.      *  
  5.      * @return 
  6.      */  
  7.     public static ObjectMapper om() {  
  8.         ObjectMapper mapper = new ObjectMapper();  
  9.         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,  
  10.                 false);  
  11.         mapper.configure(  
  12.                 DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS,  
  13.                 true);  
  14.         return mapper;  
  15.     }  
  16. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章