//反序列化为List<User> 集合,1需要通过 TypeReference 来具体传递值
List<User> user2 = objectMapper.readValue(str, new TypeReference<List<User>>() {});
for(User user: user2) {
System.out.println(user);
}
//通过 JavaType 来进行处理返回
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, User.class);
List<User> user3 = objectMapper.readValue(str, javaType);
for(User user : user3) {
System.out.println(user);
}
String str= mapper.writeValueAsString(user);
System.out.println("对象转为字符串:" + str);
User user = mapper.readValue(str, User.class);
System.out.println("json字符串转为对象:" + user);
其他设置:
//序列化的时候序列对象的所有属性
objectMapper.setSerializationInclusion(Include.ALWAYS);
//反序列化的时候如果多了其他属性,不抛出异常
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//如果是空对象的时候,不抛异常
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
参考:https://blog.csdn.net/zxc_user/article/details/79713586