使用Jackson 如何把json字符串反序列化为List呢?
(List中是自定义对象)
先看下常规的反序列化:
@Test
public void test_reserialize(){
String jsonInput = "{\"addrr\":{\"country\":\"中国\",\"state\":\"湖北省\",\"street\":\"清河\"},\"age\":25,\"hobby\":\"\",\"name\":\"黄威\"}";
ObjectMapper mapper = new ObjectMapper();
Student student;
try {
student = mapper.readValue(jsonInput, Student.class);
System.out.println(student.getAddrr().getStreet());
System.out.println(student.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
运行结果:
序列化
@Test
public void test_004(){
List<Teacher> list=new ArrayList<Teacher>();
Teacher t=new Teacher();
t.setId(2);
t.setName("雄鹰表");
t.setTitle("aa");
list.add(t);
t=new Teacher();
t.setId(3);
t.setName("陈定生");
t.setTitle("bb");
list.add(t);
t=new Teacher();
t.setId(4);
t.setName("张阿勇");
t.setTitle("cc");
list.add(t);
ObjectMapper mapper = new ObjectMapper();
String content;
try {
content = mapper.writeValueAsString(list);
System.out.println(content);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
运行结果:
[{“id”:2,”title”:”aa”,”name”:”雄鹰表”},{“id”:3,”title”:”bb”,”name”:”陈定生”},{“id”:4,”title”:”cc”,”name”:”张阿勇”}]
反序列化
把上述json字符串反序列化为List
代码如下:
@Test
public void test_006(){
String jsonInput="[{\"id\":2,\"title\":\"aa\",\"name\":\"雄鹰表\"},{\"id\":3,\"title\":\"bb\",\"name\":\"陈定生\"},{\"id\":4,\"title\":\"cc\",\"name\":\"张阿勇\"}]";
ObjectMapper mapper = new ObjectMapper();
List student;
try {
student = mapper.readValue(jsonInput, List.class);
System.out.println(student.size());
} catch (Exception e) {
e.printStackTrace();
}
}
运行时
没有达到预期效果,虽然反序列化成了List,但是并不是List< Teacher>,而是List< HashMap>
如何解决这个问题呢?
解决方法:使用mapper.getTypeFactory().constructParametricType
/**
* 获取泛型的Collection Type
* @param collectionClass 泛型的Collection
* @param elementClasses 元素类
* @return JavaType Java类型
* @since 1.0
*/
public static JavaType getCollectionType(ObjectMapper mapper,Class<?> collectionClass, Class<?>... elementClasses) {
return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
@Test
public void test_006(){
String jsonInput="[{\"id\":2,\"title\":\"aa\",\"name\":\"雄鹰表\"},{\"id\":3,\"title\":\"bb\",\"name\":\"陈定生\"},{\"id\":4,\"title\":\"cc\",\"name\":\"张阿勇\"}]";
ObjectMapper mapper = new ObjectMapper();
List student;
try {
student = mapper.readValue(jsonInput, getCollectionType(mapper, List.class, Teacher.class));
System.out.println(student.size());
} catch (Exception e) {
e.printStackTrace();
}
}