1. 程式人生 > >利用Jackson框架將json字串轉換成泛型List

利用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