1、查看Index的对象序列化方法发现是用的Gson做对象序列化如图

 

 而Gson默认的时间处理adapter只有争对Date做格式化处理,并未对LocalDate做处理,会调用

 

 

 

默认的时间处理器将LocalDate按照年,月,日的方式存储为多个字段,所以我们要对LocalDate

2、在GsonBuilder里面有一个registerTypeAdapter方法可以供我们新增一些处理器

 

3、可以通过实现 GsonBuilderCustomizer 来写入我们自定义的adapter,代码如下

@Configuration
public class GsonBuilderCustomizerConfig implements GsonBuilderCustomizer {

@Override
public void customize(GsonBuilder gsonBuilder) {
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateSerializerAdapter())
.registerTypeAdapter(LocalDate.class, new LocalDateDeserializerAdapter())
.registerTypeAdapter(LocalDateTime.class,new LocalDateTimeSerializerAdapter())
.registerTypeAdapter(LocalDateTime.class,new LocalDateTimeDeserializerAdapter());
}

class LocalDateSerializerAdapter implements JsonSerializer<LocalDate>{

@Override
public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
}

class LocalDateDeserializerAdapter implements JsonDeserializer<LocalDate>{

@Override
public LocalDate deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return LocalDate.parse(jsonElement.getAsString(),DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
}

class LocalDateTimeSerializerAdapter implements JsonSerializer<LocalDateTime>{

@Override
public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}

class LocalDateTimeDeserializerAdapter implements JsonDeserializer<LocalDateTime>{

@Override
public LocalDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return LocalDateTime.parse(jsonElement.getAsString(),DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}
}

 这样我们在写入数据的时候就可以将LocalDate用字符串的方式写入到es