springmvc默认的消息转换器是使用的MappingJackson2HttpMessageConverter
, 其核心类就是ObjectMapper.
先看一下面一个示例
@RestController public class TestObjectMapperController { @GetMapping("/getUser") public User getUser() { User user = new User(); user.setUId("1"); user.setDate(new Date()); user.setLocalDateTime(LocalDateTime.now()); return user; } } @Data class User { private String uId; private Date date; private LocalDateTime localDateTime; }
启动springboot项目,浏览器请求/getUser接口,结果就是下面这个破样子
序列化后的时间格式明显不是我们想要的, 可以通过以下配置对其进行修改
@Configuration public class ObjectMapperConfig { @Bean public Jackson2ObjectMapperBuilderCustomizer customJackson() { return jacksonObjectMapperBuilder -> { //若POJO对象的属性值为null,序列化时不进行显示 jacksonObjectMapperBuilder.serializationInclusion(JsonInclude.Include.NON_NULL); //针对于Date类型,文本格式化 jacksonObjectMapperBuilder.simpleDateFormat("yyyy-MM-dd HH:mm:ss"); //针对于JDK新时间类。序列化时带有T的问题,自定义格式化字符串 JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); jacksonObjectMapperBuilder.modules(javaTimeModule); }; } }
添加以下配置后, 重启项目,请求/getUser接口,结果如下
===============补充示例===============
public class TestObjectMapper { @Test public void test1() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); //POJO无public的属性或方法时,不报错 objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); //null值字段不显示 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); //美化JSON输出 objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // 序列化JSON串时,在值上打印出对象类型 A a = new A(); B b = new B(); b.setSalary(100.5D); b.setAge(18); a.setB(b); a.setId("123"); a.setUsername("admin"); a.setDate(new Date()); String string = objectMapper.writeValueAsString(a); //解析对象 System.out.println(string); } } @Data class A { private String id; private String username; private Date date; private B b; } @Data class B { private Double salary; private Integer age; }