首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jackson用Java 8反序列化elasticsearch作为LocalDateTime

Jackson用Java 8反序列化elasticsearch作为LocalDateTime
EN

Stack Overflow用户
提问于 2019-07-18 16:13:39
回答 2查看 8.8K关注 0票数 4

我们在elasticsearch索引中有一个用long填充的日期字段。

实地测绘是:

代码语言:javascript
复制
@Field(type = FieldType.Date)
@JsonFormat(shape = JsonFormat.Shape.NUMBER_INT)
private LocalDateTime created;

我在这个配置中使用Jackson JavaTimeModuleJdk8Module

代码语言:javascript
复制
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
   return new ElasticsearchRestTemplate(client(), new CustomEntityMapper());
}

public static class CustomEntityMapper implements EntityMapper {

        private final ObjectMapper objectMapper;

        public CustomEntityMapper() {
            //we use this so that Elasticsearch understands LocalDate and LocalDateTime objects
            objectMapper = new ObjectMapper()
                              .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                              .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
                              .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
                              .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
                              .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
                              //MUST be registered BEFORE calling findAndRegisterModules
                              .registerModule(new JavaTimeModule())
                              .registerModule(new Jdk8Module());
            //only autodetect fields and ignore getters and setters for nonexistent fields when serializing/deserializing
            objectMapper.setVisibility(objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
                            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                            .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
            //load the other available modules as well
            objectMapper.findAndRegisterModules();
        }

        @Override
        public String mapToString(Object object) throws IOException {
            return objectMapper.writeValueAsString(object);
        }

        @Override
        public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
            return objectMapper.readValue(source, clazz);
        }
}

但是,当我尝试使用字段解析索引中的实体时,例如:

代码语言:javascript
复制
"created" : 1563448935000

我收到一个错误:

代码语言:javascript
复制
com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (VALUE_NUMBER_INT), expected VALUE_STRING: Expected array or string.

我认为,将long反序列化到约会是可能的,但我不知道我错过了什么。

如果我将它映射到Long,当然,如果该值存储为String,并且我们在@JsonFormat中对其进行了适当的格式化和格式化,那么它就会正常工作。但是也有可能拥有long->LocalDateTime吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-07-18 20:49:34

要从LocalDateTime的时代起毫秒内构建1970-01-01T00:00:00Z,我们需要一个时区。在版本2.9.9中,当出现毫秒时,它将引发异常:

java.time.LocalDateTime不允许使用原始时间戳(1563448935000):需要附加信息,如偏移量或时区(请参阅类Javadocs)

但是我们可以实现反序列化器,它将尝试使用默认时区来实现这一点。示例实现如下所示:

代码语言:javascript
复制
class MillisOrLocalDateTimeDeserializer extends LocalDateTimeDeserializer {

    public MillisOrLocalDateTimeDeserializer() {
        super(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }

    @Override
    public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        if (parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
            long value = parser.getValueAsLong();
            Instant instant = Instant.ofEpochMilli(value);

            return LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
        }

        return super.deserialize(parser, context);
    }

}

使用ZoneOffset.UTC。在您的情况下,您可以提供您的或使用系统默认。示例用法:

代码语言:javascript
复制
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // override default
        javaTimeModule.addDeserializer(LocalDateTime.class, new MillisOrLocalDateTimeDeserializer());

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(javaTimeModule);

        String json = "{\"created\":1563448935000}";
        System.out.println(mapper.readValue(json, Created.class));

    }
}

class Created {

    private LocalDateTime created;

    // getters, setters, toString
}

以上代码打印:

代码语言:javascript
复制
Created{created=2019-07-18T11:22:15}

编辑:使用Jackson 2.9.0,由于问题,提供的代码将不会被调用,因为在注册定制模块之后调用的findAndRegisterModules将覆盖它。删除该调用将使整个场景工作。如果以上不适用于您的版本,则需要调试默认实现并找到原因。

票数 10
EN

Stack Overflow用户

发布于 2021-05-17 13:57:23

使用Instant作为日期的杰克逊字段类型。这就简化了一切!您只需要注册模块:https://github.com/FasterXML/jackson-modules-java8

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57098784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档