转载自:http://www.cnblogs.com/quanyongan/archive/2013/04/16/3024993.html
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 }