Json timestamp轉LocalDateTime報錯JSON parse error: raw timestamp (1595952000000) not allowed for `java.time.LocalDateTime`: need additional information such as an offset or time-zone (see class Javadocs)


異常信息

Error while extracting response for type [class com.xxx.xxx.provider.user.entity.User] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: raw timestamp (1595952000000) not allowed for `java.time.LocalDateTime`: need additional information such as an offset or time-zone (see class Javadocs);
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: raw timestamp (1595952000000) not allowed for `java.time.LocalDateTime`: need additional information such as an offset or time-zone
(see class Javadocs)\n at [Source: (PushbackInputStream); line: 1, column: 234] (through reference chain: com.xxx.xxx.provider.user.entity.User[\"birthday\"])

在數據庫查詢后,往調用方返回的序列化結果時,做了一層轉化,把LocalDataTime轉為時間戳,但是在內部feign調用時,接收方需要LocalDataTime,此時就出現這個異常.

解決辦法加一個LocalDataTime序列化的配置類,在接受時再轉一次.

@Configuration
public class LocalDateTimeSerializerConfig {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer());
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer());
        };
    }

    /**
     * 序列化
     */
    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException {
            if (value != null) {
                long timestamp = value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                gen.writeNumber(timestamp);
            }
        }
    }

    /**
     * 反序列化
     */
    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
                throws IOException {
            long timestamp = p.getValueAsLong();
            if (timestamp > 0) {
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
            } else {
                return null;
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM