gpt4 book ai didi

java - 使用 toObject 方法将 Snapshot 转换为 POJO 时,将包含 Date 对象的代码转换为 Firebase.Timestamp 对象的最佳方法

转载 作者:行者123 更新时间:2023-12-02 11:03:41 25 4
gpt4 key购买 nike

我注意到每次运行应用代码时都会收到以下警告:

W/Firestore: (0.6.6-dev) [Firestore]: The behavior for java.util.Date objects stored in Firestore is going to change AND YOUR APP MAY BREAK. To hide this warning and ensure your app does not break, you need to add the following code to your app before calling any other Cloud Firestore methods:

FirebaseFirestore firestore = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setTimestampsInSnapshotsEnabled(true)
.build();
firestore.setFirestoreSettings(settings);

With this change, timestamps stored in Cloud Firestore will be read back as com.google.firebase.Timestamp objects instead of as system java.util.Date objects. So you will also need to update code expecting a java.util.Date to instead expect a Timestamp. For example:

// Old:
java.util.Date date = snapshot.getDate("created_at");
// New:
Timestamp timestamp = snapshot.getTimestamp("created_at");
java.util.Date date = timestamp.toDate();

Please audit all existing usages of java.util.Date when you enable the new behavior. In a future release, the behavior will be changed to the new behavior, so if you do not follow these steps, YOUR APP MAY BREAK.

如果您从 DocumentSnapshot 中单独获取每个文档对象,则警告提供的示例建议了转换代码的最佳方法。

我的问题是 - 如果您使用 .toObject() 会怎样? DocumentSnapshot 上的方法直接从中获取 POJO,在这种情况下是否有更新代码/数据模型的建议/优化方法?

因为以下场景java.util.Date目前已在应用程序中使用 -

  1. 由于整个应用程序中有很多地方使用了日期对象。
  2. 此外,日期也是一些 map 数据类型对象的值(例如 Map<String, Date> )。如何在不做太大改动的情况下处理 documentSnapshot 中此类数据对象的代码转换?

One way I have already thought is to update the POJO's with java.util.Date fields to com.google.firebase.Timestamp as well as in the Map<K, V> implementations. After that update the code implementation by adding .toDate() after the Timestamp field calls. But this way doesn't seem optimized.

最佳答案

使用 toObject() 时,Firestore SDK 会自动将 Timestamp 文档字段转换为 POJO 类成员的 Date 对象。它能够在运行时检测类型以进行转换。

您引用的警告是针对在直接访问快照数据时尝试假定对象类型的代码。

关于java - 使用 toObject 方法将 Snapshot 转换为 POJO 时,将包含 Date 对象的代码转换为 Firebase.Timestamp 对象的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51143419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com