【已解决】OpenFegin调用时LocalDate时间转换异常处理

异常

主要异常

Caused by: java.time.format.DateTimeParseException: 
Text '2000-02-09 16:05:20' could not be parsed at index 10

全部异常信息

SON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2000-02-09 16:05:20": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2000-02-09 16:05:20' could not be parsed at index 10; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2000-02-09 16:05:20": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2000-02-09 16:05:20' could not be parsed at index 10

原因 :转换出错

解决方式

方式一 实现FeignFormatterRegistrar

@Component
public class LocalDateFeignFormatterRegistrar implements FeignFormatterRegistrar {
	@Override
	public void registerFormatters(FormatterRegistry registry) {
		registry.addConverter(LocalDate.class, String.class, new Converter<LocalDate, String>() {
			@Override
			public String convert(LocalDate source) {
				return LocalDateTimeUtil.format(source, DatePattern.NORM_DATETIME_PATTERN);
        }
		});
	}
}

方式二 添加对象映射

@Configuration
@AutoConfigureBefore(JacksonAutoConfiguration.class)
public class JacksonConfiguration {
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 对象映射
     */
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper()
                //指定要序列化的域
                .setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY)

                // 不将日期写为时间戳
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                // 忽略未知属性
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                // 对象属性为空时可以序列化
                .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
                .registerModule(new Java8TimeModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaLongTypeModule())
                .registerModule(new SimpleModule());

        objectMapper.registerModule(new Jdk8Module());
        objectMapper.setDateFormat(new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT));
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        objectMapper.registerModule(javaTimeModule).registerModule(new ParameterNamesModule());

        //设置null为""
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });

        JsonKit.setObjectMapper(objectMapper);
        return objectMapper;
    }


    /**
     * 序列化配置 ObjectMapper 对象
     * 会记录被序列化的类型信息, 反序列化时直接能反序列化回原始的对象类型
     */
    @Bean
    public ObjectMapper typeObjectMapper(ObjectMapper objectMapper) {
        // 对象映射器
        ObjectMapper copy = objectMapper.copy();
        // 序列化是记录被序列化的类型信息
        //指定序列化输入的类型为非最终类型,除了少数“自然”类型(字符串、布尔值、整数、双精度),它们可以从 JSON 正确推断; 以及所有非最终类型的数组
        copy.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY)
                // null 值不序列化
                .setSerializationInclusion(JsonInclude.Include.NON_NULL);
        JsonKit.setTypeObjectMapper(copy);
        return copy;
    }
}

方式三 在对应的数据上添加注解

    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime createTime;
    /**
     * 修改时间
     *
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime modifyTime;

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值