Jackson LocalDateTime的序列化

jackson对LocalDateTime的序列化依赖 JavaTimeModule,如下:

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

实际过程中发现序列化下来是一个数组,例如 [2020,5,25,8,37,40] 就是2020-05-25 08:37:40 , https://stackoverflow.com/questions/41257905/localdatetime-not-serialized-as-a-timestamp 这里解释了Jackson为什么会将LocalDateTime、LocalDate等解析成数组

实际使用过程中,在对 2020-05-25 08:37:00这个时间进行解析时,数组将会是 [2020,5,25,8,37],长度是5而不是6

g.writeNumber(value.getYear());
g.writeNumber(value.getMonthValue());
g.writeNumber(value.getDayOfMonth());
g.writeNumber(value.getHour());
g.writeNumber(value.getMinute());
final int secs = value.getSecond();
final int nanos = value.getNano();
if ((secs > 0) || (nanos > 0)) {
  g.writeNumber(secs);
  if (nanos > 0) {
      if (useNanoseconds(provider)) {
          g.writeNumber(nanos);
      } else {
          g.writeNumber(value.get(ChronoField.MILLI_OF_SECOND));
      }
  }
}   

如果需要统一返回,可以覆盖它的LocalDateTime的序列化处理

public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {

	@Override
	public void serialize(LocalDateTime value, JsonGenerator g, SerializerProvider serializers) throws IOException {
		g.writeStartArray();
		g.writeNumber(value.getYear());
		g.writeNumber(value.getMonthValue());
		g.writeNumber(value.getDayOfMonth());
		g.writeNumber(value.getHour());
		g.writeNumber(value.getMinute());
		g.writeNumber(value.getSecond());
		g.writeEndArray();
	}

}

JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
mapper.registerModule(javaTimeModule);
java读取win10 chrome(80+) cookie
camunda入门