Jackson将json字符串转换成泛型List
2019獨角獸企業重金招聘Python工程師標準>>>
?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); ??
? ? }
?
轉載于:https://my.oschina.net/u/1018004/blog/338214
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Jackson将json字符串转换成泛型List的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos和redhat启用epel软
- 下一篇: Nagios---NRPE