2

我正在尝试使用 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;
        }
    }
}
4

1 回答 1

0

我在这里做了一个测试,并检查了它是否document.get("zonedDateTime")返回了一个org.bson.Document实例。所以,我刚刚将此对象传递给编解码器:

import org.bson.BsonReader;
import org.bson.Document;
import org.bson.json.JsonReader;
import org.bson.codecs.DecoderContext;

Object object = document.get("zonedDateTime");

ZonedDateTimeCodec codec = (ZonedDateTimeCodec) codecRegistry.get(ZonedDateTime.class);
BsonReader reader = new JsonReader(((Document) object).toJson());
ZonedDateTime zdt = codec.decode(reader, DecoderContext.builder().build());
System.out.println(zdt);

ZonedDateTime变量 ( )将zdt被正确创建(在我的测试中,我得到了2017-07-13T18:07:13.603+01:00[Europe/London])(伦敦时区的当前日期/时间)。

于 2017-07-13T17:17:46.930 回答