Firestore google.cloud.Timestamp解析

问题描述 投票:0回答:2

当我收到firestore DocumentSnapshot字段(时间戳)时:

DocumentSnapshot snapshot = message.getPayload().getDocumentSnapshot();
Object o = snapshot.get("fieldName);

一切正常,Object o用真实数据Thu Jan 10 00:00:00 CET 2019实例化

但是当我尝试以google.cloud.Timestamp接收该字段时:

DocumentSnapshot snapshot = message.getPayload().getDocumentSnapshot();
Timestamp ts = snapshot.getTimestamp("fieldName");

Timestamp ts = (Timestamp) snapshot.get("fieldName");失败,错误java.util.Date cannot be cast to com.google.cloud.Timestamp

有人可以澄清这种行为,我应该如何从DocumentSnapshot访问广告检索google.cloud.Timestamp对象?我只有Timestamp对象有这个问题,每隔一个类型正常解析。

编辑,添加更多代码:

访问firestore:

    @Bean
    public FirestoreGateway registerFirestoreGateway(FirestoreGatewayProperties properties) throws IOException {
        Resource resource = new ClassPathResource(properties.getFirestoreConfiguration());
        InputStream configuration = resource.getInputStream();

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(configuration))
                .setDatabaseUrl(properties.getDatabaseUrl())
                .build();
        FirebaseApp.initializeApp(options);

        return new FirestoreGateway(FirestoreClient.getFirestore());
    }

Firestore快照侦听器:

@EventListener(ApplicationReadyEvent.class)
public void listenToRequestCommands() {
    firestoreConnection.listCollections().forEach(collectionReference -> {
        collectionReference
                .document(properties.getFirestoreCommand())
                .addSnapshotListener((snapshot, e) -> {
                            Object o = snapshot.get("timestamp");
                            Timestamp ts = (Timestamp) snapshot.get("timestamp");
                        }
                );
    });
}

Object o正常解析为正确的值,而同一事件的Timestamp ts抛出“java.util.Date无法转换为com.google.cloud.Timestamp”

数据库中的时间戳字段定义:

enter image description here

java firebase google-cloud-firestore
2个回答
1
投票

您收到以下错误:

java.util.Date无法强制转换为com.google.cloud.Timestamp

因为在您的数据库中,timestamp属性的类型为Date而不是Timestamp。 Java中没有办法将Date类型的对象强制转换为com.google.firebase.Timestamp类型的对象,因为它们之间没有继承关系。

要解决此问题,您需要使用以下代码行将该属性作为Date获取:

Date timestamp = snapshot.getDate("timestamp");

编辑:

当您将字段设置为timestamp类型时,您将其设置为Timestamp,它是另一个包的一部分。见,class Timestamp extends Date。所以timestamp对象是一个Date,因为它继承自Date类。

作为结论,来自Timestamp包的com.google.firebase类与Timestamp包中的java.sql类不同,后者与Timestamp包中存在的java.security类不同。

Aaditi:

根据您的评论,使用时:

(java.util.Date) snapshot.get("timestamp");

这意味着snapshot.get("timestamp")返回的对象被转换为Date,这基本上是相同的。换句话说,您告诉编译器无论返回什么对象,都将其视为Date对象。它的工作原理是因为数据库中属性的类型是Date而不是Firebase Timestamp


1
投票

Kotlin解决方案对我有用:

val timestamp: Date = document.getDate("timestamp") as Date
© www.soinside.com 2019 - 2024. All rights reserved.