Ios 如何在swift中解析Firebase FDatasnapshot json数据
我在从Firebase获取数据时遇到问题 模式是Ios 如何在swift中解析Firebase FDatasnapshot json数据,ios,json,swift,firebase,Ios,Json,Swift,Firebase,我在从Firebase获取数据时遇到问题 模式是 { title: "dog", images: { main: "dog.png", others: { 0: "1.png", 1: "2.png", 2: "3.png" } } } 如何将FDataSnapshot解析为swift模型???Firebase是一个NoSQL JSON数据库,没有模式
{
title: "dog",
images: {
main: "dog.png",
others: {
0: "1.png",
1: "2.png",
2: "3.png"
}
}
}
如何将FDataSnapshot解析为swift模型???Firebase是一个NoSQL JSON数据库,没有模式和表。数据以具有节点的“树”结构存储;父母和孩子 您不需要解析Firebase JSON数据就可以访问它,您可以直接访问它 FDataSnapshots包含一个.key,它是Firebase和.value中的父项。值可以包含一个或多个节点。该值将具有表示快照内数据的key:Value对 因此,对于您的示例,您将有一个像这样的Firebase结构
dogs
dog_id_0
title: "dog"
type: "Alaskan Malamute"
images:
main: "dog.png"
others:
0: "1.png"
1: "2.png"
dog_id_1
title: "another dog"
type: "Boxer"
images:
main: "another_dog.png"
others:
0: "3.png"
1: "4.png"
所以,假设您希望每次读取一个dog_id_x节点,并打印一些值
var ref = Firebase(url:"https://your-app.firebaseio.com/dogs")
ref.observeEventType(.ChildAdded, withBlock: { snapshot in
println(snapshot.value.objectForKey("title"))
println(snapshot.value.objectForKey("type"))
})
这将输出
dog
Alaskan Malamute
another dog
Boxer
dog_id_0和dog_id_1是使用Firebase childByAutoId创建的节点名
您可以同样轻松地创建一个Dog类,并将FDataSnapshot传递给它,它将从快照中的数据填充该类。2017年2月更新,Swift 3 Xcode 8 由于Swift3和Firebase在提出此问题时发生了很多变化,我将提供一种解析Firebase数据的更新方法:
let userID = FIRAuth.auth()?.currentUser?.uid
//I am registering to listen to a specific answer to appear
self.ref.child("queryResponse").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
//in my case the answer is of type array so I can cast it like this, should also work with NSDictionary or NSNumber
if let snapshotValue = snapshot.value as? NSArray{
//then I iterate over the values
for snapDict in snapshotValue{
//and I cast the objects to swift Dictionaries
let dict = snapDict as! Dictionary<String, Any>
}
}
}) { (error) in
print(error.localizedDescription)
}
let userID=FIRAuth.auth()?.currentUser?.uid
//我注册是为了听一个具体的答案出现
self.ref.child(“queryResponse”).child(userID!).observeSingleEvent(of:.值,其中:{(快照))位于
//在我的例子中,答案是数组类型,所以我可以像这样强制转换它,还应该与NSDictionary或NSNumber一起使用
如果让snapshotValue=snapshot.value为?NSArray{
//然后我迭代这些值
用于snapshotValue中的snapDict{
//我把这些东西放到了斯威夫特字典里
让dict=snapDict作为字典
}
}
}){(错误)在
打印(错误。本地化描述)
}
您可以使用字典对其进行解析,也可以使用my
您案例的示例代码:
func main(){
let root=SnapshotParser().parse(snap: Snapshot, type: Root.self)
}
class Root: ParsableObject {
var title:String?=nil
var images:Images?=nil
required init(){}
func bindProperties(binder: SnapshotParser.Binder) {
binder.bindField(name: "title", field: &title)
binder.bindObject(name: "images", field: &images)
}
}
class Images: ParsableObject {
var main:String?=nil
var others:[Int:String]?=nil
required init(){}
func bindProperties(binder: SnapshotParser.Binder) {
binder.bindField(name: "main", field: &main)
binder.bindDictionary(name: "others", dict: &others)
}
}
试着玩这个:
func makeItems(from snapshot: DataSnapshot) -> [SimpleItem] {
var items = [SimpleItem]()
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshots {
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let item = SimpleItem(parentKey: snap.key, dictionary: postDictionary)
items.append(item)
}
}
}
return items
}
func makeItems(来自快照:DataSnapshot)->[SimpleItem]{
变量项=[SimpleItem]()
如果让快照=snapshot.children.allObjects为?[DataSnapshot]{
用于管理单元快照{
如果让postDictionary=snap.value作为字典{
let item=SimpleItem(parentKey:snap.key,dictionary:postDictionary)
items.append(项目)
}
}
}
退货项目
}
func加载项(){
firebaseService.databaseReference
.儿童(“项目”)
.queryOrdered(byChild:“日期”)
.queryLimited(toLast:5)
.observeSingleEvent(of:.值){中的快照
let items=self.makeItems(from:snapshot)
print(这将解析单个对象中的所有快照子对象,并将其转换为数组,您可以轻松地解析带有索引的子对象数组
如果让snap=snapshot.children.allObjects为?[DataSnapshot]{
打印(快照)
对于snap.enumerated()中的(index,val){
打印(“值”)
打印(val)
打印(val.value)
}
}
谢谢你的回答。那么我如何才能在json中获得数组???我想知道如何将带有“main”的“others”数据获取到类或变量。我的意思是从“images”键值解析到类或变量~!读取“others”数组就像读取任何其他键值对一样。当你获得.objectForTitle(“others”)时值将是数组。但是,您可能希望以不同的方式设置您的结构,因为数组的使用是非常情境化的,通常有更好的方法来存储您的数据,从而提供更大的灵活性。数组可能是一个挑战,所以我通常避免使用它们。如果我只想使用.ChildChanged获取dog_id_0的数据,该怎么办?如果您仅我对dog_id_0感兴趣,有很多选择,这里有两个:1)专门为该节点添加一个观测者。var ref=Firebase(url:)和.ChildChanged 2)代码中的过滤器-如果snapshot.key=dog_id_0,忽略它。感谢库!)这样对我不起作用(请检查swiftlint以改进语法)
func loadItems() {
firebaseService.databaseReference
.child("items")
.queryOrdered(byChild: "date")
.queryLimited(toLast: 5)
.observeSingleEvent(of: .value) { snapshot in
let items = self.makeItems(from: snapshot)
print("This will parse all the snapshot children in the single object and convert it in array and you can easily parse the array of children with index
if let snap = snapshot.children.allObjects as? [DataSnapshot]{
print(snap)
for (index,val) in snap.enumerated(){
print("values")
print(val)
print(val.value)
}
}