java的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);
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); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
淺談@mapper引入不到引入的是@MapperScan的問題
這篇文章主要介紹了淺談@mapper引入不到引入的是@MapperScan的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10