如何在Firebase数据库中解压多层嵌套JSON [英] How to unpack multiple levels of nested JSON in Firebase Database
问题描述
在我的应用中,我通常会遇到一个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.
推荐答案
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快照阵列中获取数据
- SwiftFirebase-如何在使用queryOrdered(byChild:).queryEqual(toValue:)时获取所有k/v
- 其他有关在子节点上循环的问题
这篇关于如何在Firebase数据库中解压多层嵌套JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!