无法构造`java.time.LocalDate`的实例 - Spring boot,elasticseach,jackson

时间:2018-02-19 14:11:37

标签: java spring spring-boot elasticsearch jackson

我正在使用Spring-boot 2.0.0.M7spring-boot-starter-data-elasticsearch以及elasticsearch 5,并且我通过反序列化LocalDate字段来收到错误。

我的文档看起来像这样:

@Document(indexName= "myIndex", type = "cluster")
public class Cluster {

    @Id
    @Field
    private Long id;
    @Field
    private String name;
    @Field
    private ClusterUrl clusterUrl;
    @Field
    private ClusterVisible clusterVisible;
}

其中ClusterVisible是包含LocalDates

的子对象
public class ClusterVisible {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy")
    private LocalDate start;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy")
    private LocalDate end;
}

所以我只是查询一个集群ID,我得到了这个例外:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDate` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"id":12345,"name":"Cluster name ","clusterName":{"de":"Cluster de","it":null,"fr":null},"clusterUrl":{"de":"/url/results","it":null,"fr":null},"clusterVisible":{"start":{"year":2017,"month":"OCTOBER","dayOfMonth":9,"dayOfWeek":"MONDAY","era":"CE","dayOfYear":282,"leapYear":false,"mo"[truncated 252 chars]; line: 1, column: 388] (through reference chain: com.example.elasticsearch5.es.cluster.model.Cluster["clusterVisible"]->com.example.elasticsearch5.es.cluster.model.ClusterVisible["start"])
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1451)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1027)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1290)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2992)
    at org.springframework.data.elasticsearch.core.DefaultEntityMapper.mapToObject(DefaultEntityMapper.java:65)

我已经知道我需要为java.time api添加一些jackson依赖项,所以我补充说:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.4</version>
</dependency>

但现在这没有用。我还通过使用kibana进行查询来检查索引中的条目。查询的结果是:

...
"clusterVisible": {
    "start": {
      "year": 2017,
      "month": "OCTOBER",
      "dayOfMonth": 25,
      "dayOfWeek": "WEDNESDAY",
      "era": "CE",
      "dayOfYear": 298,
      "leapYear": false,
      "monthValue": 10,
      "chronology": {
        "id": "ISO",
        "calendarType": "iso8601"
      }
    },
    "end": {
      "year": 3000,
      "month": "JANUARY",
      "dayOfMonth": 1,
      "dayOfWeek": "WEDNESDAY",
      "era": "CE",
      "dayOfYear": 1,
      "leapYear": false,
      "monthValue": 1,
      "chronology": {
        "id": "ISO",
        "calendarType": "iso8601"
      }
    }
}

修复此错误我错过了什么?

添加:mapper.mapToObject处出现确切错误。所以我之前创建了一些new DefaultEntityMapper();行。这可能是问题吗?

@Override
public Page<Cluster> findClustersAndScoreByText(String text) {
    QueryBuilder queryBuilder = QueryBuilders.boolQuery()
            .should(QueryBuilders.queryStringQuery(text).lenient(true).defaultOperator(Operator.OR)
                    .field("name")
                    .field("svno"));

    NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder().withQuery(queryBuilder)
            .withPageable(PageRequest.of(0, 100)).build();

    DefaultEntityMapper mapper = new DefaultEntityMapper();
    ResultsExtractor<Page<Cluster>> rs = new ResultsExtractor<Page<Cluster>>() {

        @Override
        public Page<Cluster> extract(SearchResponse response) {
            ArrayList<Cluster> hotels = new ArrayList<>();
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                try {
                    Cluster cluster = mapper.mapToObject(hit.getSourceAsString(), Cluster.class);
                    cluster.setScore(hit.getScore());
                    hotels.add(cluster);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return new PageImpl<>(hotels, PageRequest.of(0, 100), response.getHits().getTotalHits());
        }
    };

    return elasticsearchTemplate.query(nativeSearchQuery, rs);
}

4 个答案:

答案 0 :(得分:2)

日期/时间格式,根据ISO 8601 “YYYY-MM-DD”,因此您的模式应为:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")

代替:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd.MM.yyyy")

另一种方法是添加 application.yml

spring:
    jackson:
        serialization:
            WRITE_DATES_AS_TIMESTAMPS: false

或直接在对象映射器中禁用此功能:

objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)

答案 1 :(得分:1)

在字段LocalDate下方的注释中添加

@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate start;

答案 2 :(得分:0)

需要安装JsonFormat JsonDeserialize JsonSerialize

private LocalDate dateOfBirth;

    @PastOrPresent(message = "must be past time or present")
    @Column(name = "date_of_birth", nullable = false, columnDefinition = "DATE")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    public LocalDate getDateOfBirth() {
        return dateOfBirth;
    }

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    public void setDateOfBirth(LocalDate dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

答案 3 :(得分:0)

您不需要@JsonFormat。您需要做的是在注释(kotlin)中使用DateFormat.date参数:

@Field(type = Date, format = date)
val created: LocalDate = now()

Elasticsearch不使用Jackson,而是使用MappingElasticsearchConverter

日期将以弹性格式保存:2020-01-02,映射将为:

 "created" : {
          "type" : "date",
          "format" : "date"
        }