如何从Firebase实时数据库获取对象数组

时间:2020-01-13 09:05:15

标签: android json kotlin firebase-realtime-database

我的实时数据库中有以下json:

{
  "stickers": {
    "StickerPack0": {
      "Sticker0": {
        "image": "https://imgur.com/SKz7cOw.png"
      },
      "Sticker1": {
        "image": "https://imgur.com/SKz7cOw.png"
      },
      "Sticker2": {
        "image": "https://imgur.com/SKz7cOw.png"
      },
      "Sticker3": {
        "image": "https://imgur.com/SKz7cOw.png"
      },
      "Sticker4": {
        "image": "https://imgur.com/SKz7cOw.png"
      },
      "price": 0.99,
      "title": "Happy Hamster"
    }
  }
}

如您所见,有pricetitle和5个对象(Sticker0Sticker1,...)的数组。

要解析它,我创建了以下实体:

data class StickerPack(
    var title: String? = null,
    var price: Double? = null,
    var stickers: List<String>? = null
)

这是我解析的方式:

query = database.child("stickers")
        query.addListenerForSingleValueEvent(object : ValueEventListener {

            override fun onCancelled(error: DatabaseError) {
                Timber.e(error.toException())
                view?.onStickerListFailed()
            }

            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {
                    val stickersFirebase = snapshot.children

                    stickersFirebase.forEach { data ->
                        val sticker = data.getValue(StickerPack::class.java)
                        stickers.add(sticker!!)
                    }

                    view?.onStickerListLoaded(stickers)
                }
            }
        })

但是在这种情况下,我只能获得titleprice之类的字段,并且无法理解如何将Sticker对象转换为字符串数组。那么,如何找到该问题的解决方案?我将不胜感激。预先感谢!

0 个答案:

没有答案