将json字符串映射为java类型
如果是简单的java bean,直接解析即可。
ObjectMapper mapper = new ObjectMapper();
Bean bean = mapper.readValue(jsonString, Bean.class);
如果是复杂类型,如list,map,可通过以下两种方法:
方法一:
ObjectMapper mapper = new ObjectMapper();
JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Bean.class);
//如果是Map类型 mapper.getTypeFactory().constructParametricType(HashMap.class,String.class, Bean.class);
List<Bean> lst = (List<Bean>)mapper.readValue(jsonString, javaType);
方法二:
ObjectMapper mapper = new ObjectMapper();
List<Bean> beanList = mapper.readValue(jsonString, new TypeReference<List<Bean>>() {});
使用方法二时注意,Bean类的构造函数一定要定义空参数的构造函数。