我刚刚按照新的(ish)Java 8时间包将许多日期转换为LocalDateTime。到目前为止,在开始尝试序列化和反序列化之前,我一直喜欢这种切换。
我如何配置Jackson以支持它们?:
LocalDateTime --serialize-> UTC时间戳--deserialize-> LocalDateTime?
这里有很多有关转换为格式化字符串的资料,但是我似乎找不到通用的utc时间戳解决方案。
答案 0 :(得分:5)
您可以为LocalDateTime
自定义序列化程序和反序列化程序,例如:
CustomLocalDateTimeSerializer
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
protected CustomLocalDateTimeSerializer(Class<LocalDateTime> t) {
super(t);
}
protected CustomLocalDateTimeSerializer() {
this(null);
}
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider sp)
throws IOException {
Long epoch = value.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
gen.writeString(epoch.toString());
}
}
CustomLocalDateTimeDesSerializer:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
class CustomLocalDateTimeDesSerializer extends StdDeserializer<LocalDateTime> {
protected CustomLocalDateTimeDesSerializer() {
this(null);
}
protected CustomLocalDateTimeDesSerializer(Class<LocalDateTime> t) {
super(t);
}
@Override
public LocalDateTime deserialize(JsonParser jsonparser, DeserializationContext context)
throws IOException {
Long timestamp = Long.parseLong(jsonparser.getText());
return LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
}
}
并使用它们:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.LocalDateTime;
public class RestObject {
private LocalDateTime timestamp = LocalDateTime.now();
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
@JsonDeserialize(using = CustomLocalDateTimeDesSerializer.class)
public LocalDateTime getTimestamp() {
return timestamp;
}
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
// {"timestamp":"1549026058"}
System.out.println(objectMapper.writeValueAsString(new RestObject()));
}
}
答案 1 :(得分:4)
以下解决方案解决了将LocalDateTime
序列化/反序列化到时间戳的任务,并且至少与spring-boot v1.5有关,并且还包括了@xingbin的{{ 3}}:
java.util.Date
具有相同的行为,则必须使用toInstant().toEpochMilli()
代替toInstant().getEpochSecond()
null
的值以反序列化ObjectMapper
时间戳序列化器类:
public class LocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public LocalDateTimeSerializer() {
super(LocalDateTime.class);
}
@Override
public void serialize(final LocalDateTime value,
final JsonGenerator generator,
final SerializerProvider provider) throws IOException {
if (value != null) {
final long mills = value.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
generator.writeNumber(mills);
} else {
generator.writeNull();
}
}
}
时间戳解串器类:
public class LocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public LocalDateTimeDeserializer() {
super(LocalDateTime.class);
}
@Override
public LocalDateTime deserialize(final JsonParser parser,
final DeserializationContext context) throws IOException {
final long value = parser.getValueAsLong();
return LocalDateTime.ofInstant(Instant.ofEpochMilli(value), DEFAULT_ZONE_ID);
}
}
对象映射器配置:
@Configuration
public class ObjectMapperConfiguration {
@Bean
public ObjectMapper objectMapper() {
final ObjectMapper objectMapper = new ObjectMapper();
final SimpleModule module = new SimpleModule();
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
objectMapper.registerModule(module);
return objectMapper;
}
}
答案 2 :(得分:0)
您可以利用the JavaTimeModule
来代替手动重写所有内容:
ObjectMapper om = new ObjectMapper();
om.registerModule(new JavaTimeModule());
om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
答案 3 :(得分:0)
这里是简单有效的方法:
@JsonFormat(shape= JsonFormat.Shape.STRING, pattern="EEE MMM dd HH:mm:ss Z yyyy")
@JsonProperty("created_at")
ZonedDateTime created_at;
这是一个问题的引号:Jackson deserialize date from Twitter to `ZonedDateTime`,因此这可能是重复的问题
答案 4 :(得分:-1)
添加 jackson-modules-java-8 依赖项:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
到您的项目,并将以下模块注册到ObjectMapper: JavaTimeModule
请参见description of JavaTimeModule以及相应的GitHub存储库jackson-modules-java-8