SpringBoot(2.5.x) 请求参数(form,json)中时间(Date,LocalDatetime)序列化与反序列化格式(全局配置))

fom表单请求时间格式化

application.yml中配置

spring:
  mvc:
    format:
      date-time: yyyy-MM-dd HH:mm:ss

json请求时间格式化

  • application.yml中配置的格式化只对Date生效
  • LocalDateTime无效
spring:
  jackson:
    time-zone: GMT+8
    # 只对 Date生效
    date-format: yyyy-MM-dd HH:mm:ss

按照其他教程里的注册到bean里,我的项目里没起作用

    /**
     * 注册到 message convert
     * 此处注册不起作用,已经替换 MappingJackson2HttpMessageConverter
     *
     * @param builder
     * @return
     */
    @Bean(name = "mapperObject")
    @Primary
    public ObjectMapper getObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper mapper = builder.createXmlMapper(false).build();
        // 未知字段失败,false
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.registerModule(new Jdk8Module());
        // 默认 LocalDateTime 格式
        JavaTimeModule timeModule = new JavaTimeModule();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DatePattern.yyyy_MM_dd_HH_mm_ss, Locale.CHINA);
        timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
        timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
        mapper.registerModule(timeModule);
        // 默认 Date 格式
        mapper.setDateFormat(new SimpleDateFormat(DatePattern.yyyy_MM_dd_HH_mm_ss));
        // 注解 Introspector 不处理会导致注解失效
        mapper.setAnnotationIntrospector(new JsonFormatIntrospector());
        // 所有序列化的对象都将按改规则进行系列化
        mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        // null 序列化
        mapper.getSerializerProvider().setNullValueSerializer(new NullValueSerializer());
        return mapper;
    }

json请求时间格式化(可行)

自定义ObjectMapper

@Configuration
public class JsonMapper {

    private static ObjectMapper mapper;

    public static ObjectMapper getMapper() {
        if (null == mapper) {
            mapper = new ObjectMapper();
            // 反序列化,未知字段不失败
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            // 序列化,空bean不失败,被 @JsonIgnore 注解的bean
            mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            mapper.registerModule(new Jdk8Module());
            // 默认 LocalDateTime 格式
            JavaTimeModule timeModule = new JavaTimeModule();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DatePattern.yyyy_MM_dd_HH_mm_ss, Locale.CHINA);
            timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
            timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
            mapper.registerModule(timeModule);
            // 默认 Date 格式
            mapper.setDateFormat(new SimpleDateFormat(DatePattern.yyyy_MM_dd_HH_mm_ss));
            // 注解 Introspector 不处理会导致注解失效
            mapper.setAnnotationIntrospector(new JsonFormatIntrospector());
            // 所有序列化的对象都将按改规则进行系列化
            mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        }
        return mapper;
    }

}

重新配置HttpMessageConverter

@Configuration
public class AdminMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List> converters) {
        // 要么将 MappingJackson2HttpMessageConverter加到前面
        // 要么删除原MappingJackson2HttpMessageConverter,否则无效
        converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof StringHttpMessageConverter || httpMessageConverter instanceof MappingJackson2HttpMessageConverter);
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        converters.add(new MappingJackson2HttpMessageConverter(JsonMapper.getMapper()));
    }
}

响应时间格式化

不管请求数据格式是form还是json,响应数据统一使用json

重写响应工具类toString()

public class Result extends HashMap {

    @ApiModelProperty("响应码")
    private static final String CODE = "code";

    @ApiModelProperty("响应描述")
    private static final String MSG = "msg";

    @ApiModelProperty("总数")
    private static final String TOTAL = "total";

    @ApiModelProperty("数据")
    private static final String DATA = "data";

    @Override
    public String toString() {
        try {
            return JsonMapper.getMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            return super.toString();
        }
    }
}
  • 使用了同一个ObjectMapper,打印响应日志和响应内容完全一致
  @ApiOperation(value = "用户修改")
    @PostMapping("/user/update")
    public Result userUpdate(@RequestBody UserUpdateRequestDTO requestDTO) {
        log.info("用户修改, 请求 {}", requestDTO);
        Result response = service.userUpdate(requestDTO);
        log.info("用户修改, 响应 {}", response);
        return response;
    }

你可能感兴趣的:(SpringBoot(2.5.x) 请求参数(form,json)中时间(Date,LocalDatetime)序列化与反序列化格式(全局配置)))