如何在Firebase数据库中解压多层嵌套JSON [英] How to unpack multiple levels of nested JSON in Firebase Database

查看:62
本文介绍了如何在Firebase数据库中解压多层嵌套JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我通常会遇到一个JSON主题,例如 message ,然后嵌套在其中是 random ID ,然后是 message 文本作为随机ID内的字符串.但是,我需要解密多个级别的随机ID.在Firebase for Swift中有可能吗?这就是我的意思:

In my app, I would regularly have a JSON topic, for example message, then nested in that is a random ID, then the message text as a string inside the random ID. But, I need to decipher multiple levels of random IDs. Is that possible in Firebase for Swift? This is what I mean:

这是我的代码:

     Database.database().reference().child("app").observe(.childAdded) { (snapshot) in
         //app is first in the JSON tree
         let dict = snapshot.value as! [String: Any]

         let msg = dict["message"] as! String

很显然,这正在崩溃该应用程序,因为它正在第一个RandomID中寻找消息".有针对这个的解决方法吗?我没有找到专门用于我所寻找的资源.谢谢你.

Obviously this is crashing the app, as it's looking for "Message" in the first RandomID. Is there a solution to this? I haven't found resources for specifically what I'm looking for. Thank you.

推荐答案

您将希望遍历 snapshot 的子级,如

You'll want to loop over the children of snapshot as shown here:

Database.database().reference().child("app").observe(.childAdded) { (snapshot) in
    for child in snapshot.children {
        let snap = child as! DataSnapshot //downcast

        let dict = snap.value as! [String: Any]
        let msg = dict["message"] as! String
    }
})

另请参阅:

这篇关于如何在Firebase数据库中解压多层嵌套JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆