Jackson 处理复杂类型(List,map)两种方法

方法一:

 String jsonString="[{'id':'1'},{'id':'2'}]";  
ObjectMapper mapper = new ObjectMapper();  
JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Bean.class);  
//如果是Map类型  mapper.getTypeFactory().constructParametricType(HashMap.class,String.class, Bean.class);  
List lst =  (List)mapper.readValue(jsonString, javaType);   

当转换完成时一定要用这个转换对象,如果不用这个对象是没有值的.如下,当我打印时这个projects对象才有值,否则projects无值 .

List projects  = mapper.readValue(subProject, mapper.getTypeFactory().constructCollectionType(List.class, AlertProjectInfo.class));
System.out.println(projects.size());

方法二:

String jsonString="[{'id':'1'},{'id':'2'}]";  
ObjectMapper mapper = new ObjectMapper();  
List<Bean> beanList = mapper.readValue(jsonString, new TypeReference<List<Bean>>() {});   

你可能感兴趣的:(json相关)