【问题标题】:Firebase Firestore Android can't deserialize objectFirebase Firestore Android 无法反序列化对象
【发布时间】:2018-05-16 11:03:09
【问题描述】:

我想将 firebase firestore 中的数据反序列化为模型 (Foo)

data class Foo(
        var timestamp: Int = 0,
        var title: String = "",
        var question: String = "",
        var category: String = "",
        var content: String = "",
        var link: String = ""
) {
    fun Foo() {}
}

这样的查询:

FirebaseFirestore.getInstance().collection(COLLECTION_NAME)
                .orderBy(ORDER_KEY, Query.Direction.DESCENDING)
                .limit(LIMIT)
                .get()
        .addOnSuccessListener { snapshot ->
            snapshot.documents.forEach {
                println(it.data) // data print successfully
                // got error java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type com.google.firebase.firestore.Blob to int (found in field 'timestamp')
                val foo = it.toObject(Foo::class.java)
            }
        }

但出现错误java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type com.google.firebase.firestore.Blob to int (found in field 'timestamp')

我在我的 android 项目中使用 firebase 版本 11.6.2

firestore 中的数据在此屏幕截图中的位置:

知道反序列化失败的原因吗?

【问题讨论】:

  • println(it.data) 打印什么?
  • 感谢您检查打印数据后,我发现了一个无效数据,其中{timestamp=blob, title=blob, category=blob...} 其他数据正常``{timestamp=1135129980, title=jkjk, category=xys..}`

标签: android firebase kotlin google-cloud-firestore


【解决方案1】:

尝试使用:

var timestamp: Blob

而不是:

var timestamp: Int = 0

然后你可以从 Blob 对象中使用这个方法:

https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/Blob

【讨论】:

  • 谢谢,但不幸的是它不起作用Could not deserialize object. Failed to convert value of type com.google.firebase.firestore.Blob to String (found in field 'timestamp')
  • 有趣,如果可能的话(尚未尝试),我如何使用 blob 作为时间戳?我在存储数据时在 Firestore 中使用数字
  • 为什么不在 Firestore 上使用整数?
  • 如果您在firebase控制台中手动输入数据,唯一的选择是数字
【解决方案2】:

我尝试使用 Blog 和 Int 变量类型,但它们不适用于 Firebase 的时间戳。然后,我使用了以下方法,它工作正常:

import java.util.*
val timestamp: Date? =  null

我希望它也对你有用。

【讨论】:

    【解决方案3】:

    我认为您在模型类中使用了错误的数据类型。

    如果您的数据类型在 firestore 集合中是 timestamp,则使用 Date 数据类型在您当前使用 int 的模型中添加时间戳。

    在 Java 中使用这个。

     public Date createdAt;
     public String createdBy;
    

    对于 kotlin 使用这个。

     val timestamp: Date? = null,
     var title: String = "",
     var question: String = "",
     var category: String = "",
     var content: String = "",
     var link: String = ""
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-29
      • 2016-12-30
      • 2014-08-04
      • 2015-05-29
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      相关资源
      最近更新 更多