如何在JSON中获取数据?

时间:2016-10-05 18:44:29

标签: ios json swift firebase firebase-realtime-database

我的数据是:

{   "Users" : {
    "Info" : {
      "GLjqemedMVRK1mgZVpPaIOuMuNx1" : {
        "adi" : "e e",
        "aracMarkasi" : "HONDA",
        "aracModeli" : "Civic",
        "eposta" : "a@a.co",
        "motorHacmi" : "1.6"
      },
      "SLtt56YlVsRfjrnAyBlUNdEakly2" : {
        "adi" : "e g",
        "aracMarkasi" : "SEAT",
        "aracModeli" : "Leon",
        "eposta" : "eg@gmail.com",
        "motorHacmi" : "1.4 Tsi"
      }
    }   
}
}

然后我检索数据

let databseRef = FIRDatabase.database().reference(fromURL: "https://ffs.firebaseio.com/Users/Info/")
databseRef.queryOrderedByKey().observe(.childAdded, with: { snapshot in

            let adi = snapshot.value(forKey: "adi")
            let eposta = snapshot.value(forKey: "eposta")
            let aracMarkasi = snapshot.value(forKey: "aracMarkasi")
            let aracModeli = snapshot.value(forKey: "aracModeli")
            let motorHacmi = snapshot.value(forKey: "motorHacmi")


        })

它返回错误:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<FIRDataSnapshot 0x78f6d5b0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key adi.'

我如何获取数据?请注意,GLjqemedMVRK1mgZVpPaIOuMuNx1SLtt56YlVsRfjrnAyBlUNdEakly2是用户uid

1 个答案:

答案 0 :(得分:2)

尝试: -

FIRDatabase.database().reference().child("Users/Info").observeSingleEvent(of: .childAdded, with: {(snap) in

        if let snapDict = snap.value as? [String:AnyObject]{

            for each in snapDict{

                print(each)
                let adi = each.value["adi"]
                let eposta = each.value["eposta"]
                let aracMarkasi = each.value["aracMarkasi"]
                let aracModeli = each.value["aracModeli"]
                let motorHacmi = each.value["motorHacmi"]

            }
        }
    })