Firestore - 如何在Kotlin中排除数据类对象的字段

pro*_*m85 9 android kotlin firebase google-cloud-firestore

这里的Firestore解释了我如何使用简单的类直接将它们与firestore一起使用:https://firebase.google.com/docs/firestore/manage-data/add-data

如何将字段标记为已排除?

data class Parent(var name: String? = null) {
    // don't save this field directly
    var questions: ArrayList<String> = ArrayList()
}
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 8

由于Kotlin为字段创建了隐式getter和setter,因此需要使用@Exclude注释setter 以告诉Firestore不要使用它们.Kotlin的语法如下:

data class Parent(var name: String? = null) {
    // questions will not be serialized in either direction.
    var questions: ArrayList<Child> = ArrayList()
        @Exclude get
}
Run Code Online (Sandbox Code Playgroud)

  • 你不是在你的例子中注释了 getter 吗?为什么你说setter需要注释? (2认同)

sin*_*enm 8

我意识到这已经太晚了,但我偶然发现了这一点,并认为我可以提供另一种语法,希望有人会发现它有用.

data class Parent(var name: String? = null) {
    @get:Exclude
    var questions: ArrayList<Child> = ArrayList()
}
Run Code Online (Sandbox Code Playgroud)

这样做的一个好处是,在我看来,它看起来更清晰,但主要的好处是它允许排除数据类构造函数中定义的属性:

data class Parent(
    var name: String? = null,
    @get:Exclude
    var questions: ArrayList<Child> = ArrayList()
)
Run Code Online (Sandbox Code Playgroud)