我正在尝试使用 MongoDB Codec 功能以ZonedDateTime
自定义格式读取和写入 Java 对象到 Mongo。
插入文档工作得很好,但我很难理解如何让 Mongo 返回一个ZonedDateTime
.
我编写了以下测试用例来尝试和演示:
public class ZonedDateTimeTest {
@Test
public void serializeAndDeserializeZonedDateTime() throws Exception {
CodecRegistry codecRegistry = fromRegistries(
CodecRegistries.fromCodecs(new ZonedDateTimeCodec()),
MongoClient.getDefaultCodecRegistry()
);
MongoClient mongoClient = new MongoClient(
"localhost:27017",
MongoClientOptions.builder()
.codecRegistry(codecRegistry)
.build()
);
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Europe/London"));
MongoCollection<Document> collection = mongoClient
.getDatabase("test")
.getCollection("test");
// Insert a document
collection.insertOne(new Document("_id", 1).append("zonedDateTime", zonedDateTime));
// Find the document just inserted
Document document = collection
.find(new Document("_id", 1))
.first();
// How to "get" a ZonedDateTime?
document.get("zonedDateTime");
}
private static class ZonedDateTimeCodec implements Codec<ZonedDateTime> {
@Override
public Class<ZonedDateTime> getEncoderClass() {
return ZonedDateTime.class;
}
@Override
public void encode(BsonWriter writer, ZonedDateTime value,
EncoderContext encoderContext) {
writer.writeStartDocument();
writer.writeString("dateTime", DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value));
writer.writeString("offset", value.getOffset().toString());
writer.writeString("zone", value.getZone().toString());
writer.writeEndDocument();
}
@Override
public ZonedDateTime decode(BsonReader reader, DecoderContext decoderContext) {
reader.readStartDocument();
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(
LocalDateTime.from(DateTimeFormatter.ISO_LOCAL_DATE_TIME.parse(reader.readString("dateTime"))),
ZoneOffset.of(reader.readString("offset")),
ZoneId.of(reader.readString("zone"))
);
reader.readEndDocument();
return zonedDateTime;
}
}
}