1
Java ZonedDateTime
オブジェクトをMongoDBコーデック機能を使用してカスタム形式でMongoに読み込もうとしています。カスタムMongoコーデックを使用してJavaクラスにドキュメントをデコード
文書を挿入するのは問題ありませんが、私はZonedDateTime
を返すようにMongoを取得する方法を理解するのに苦労しています。
私がしようと証明するために、次のテストケースを書いた:
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;
}
}
}
ありがとうございました。私が探していたものです。私はちょっと冗長なものがあるかもしれないと思っていたようだ。 –
@AndyMc私は非常に頻繁にMongoDbを使用しないことを認めなければなりません。 –