您可以为 自定义 序列化程序和解串器,例如: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()));
}
}