不知道是不是版本问题,但肯定是8.x的锅,就是构建完条件以后执行查询时候反序列化老是出现问题,具体如下面这行代码,还是在elastic讨论社区才找到答案:https://discuss.elastic.co/t/jsonp-mapping-exception/306992
SearchResponse<AnnouncementESDTO> searchResponse = elasticsearchClient.search(searchRequest, AnnouncementESDTO.class);
实体类配置
具体来说就是实体类反序列化出现了问题,我完整的实体类定义如下,修改两方面
- 类上增加@JsonIgnoreProperties(ignoreUnknown = true)注解,表示忽略实体类里面没有属性
- 日期字段不仅显式声明,反序列化时候指定序列化器@JsonDeserialize(using = CustomLocalDateDeserializer.class),反序列化器的配置如下
@Document(indexName = "announcement")
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class AnnouncementESDTO {
private static final String DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private static final String DATE_PATTERN = "yyyy-MM-dd";
@Id
private Long id;
private String title;
private String content;
@Field(index = true, store = true, type = FieldType.Date, format = {}, pattern = DATE_PATTERN)
@JsonDeserialize(using = CustomLocalDateDeserializer.class)
private LocalDate pubTime;
private String url;
@Field(index = false, store = true, type = FieldType.Date, format = {}, pattern = DATE_TIME_PATTERN)
@JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
private LocalDateTime createTime;
private Long articleId;
private String school;
}
自定义序列化器配置
package com.ischool.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
* @program: iSchool-Server
* @author: AlbertZhang
* @create: 2024-05-19 22:17
* @description:
**/
public class CustomLocalDateDeserializer extends JsonDeserializer<LocalDate> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return LocalDate.parse(p.getText(), formatter);
}
}
package com.ischool.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/*
* 解决es日期问题
* */
public class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return LocalDateTime.parse(p.getText(), formatter);
}
}
最后吐槽一下:世上配置千千万,JSON序列化占一半啊
文章评论