利用Jackson框架将json字符串转换成泛型List

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 static void main(String[] args) throws Exception{
	ObjectMapper mapper = new ObjectMapper();  
        JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, YourBean.class); 
        List<YourBean> lst =  (List<YourBean>)mapper.readValue(jsonString, javaType); 
    }

参考:http://www.cnblogs.com/quanyongan/archive/2013/04/16/3024993.html

猜你喜欢

转载自blog.csdn.net/m0_37224390/article/details/78412162