如何从json数组中解析数据

时间:2016-12-13 10:10:23

标签: arrays json swift

我无法从此JSON

获取 driverId
[data: [{"id":"619","driverId":"6789","starting_time":"2016-12-12 23:24:50","end_time":null}]]

这是我的完整代码

 //selector Method SESSION_STATUS_REQUEST_COMPLETE
    func afterServiceStatus(notification : NSNotification) {

        print(notification.userInfo!)
        guard let data =  notification.userInfo!["data"]  else{
        print("data have no idea ")
        return
        }

        if let driverId = notification.userInfo![0]!["driverId"] {

            print(driverId)

        }
    //        if let driverId = data["driverId"] as? String{
    //
    //           print(driverId)
    //        }


    }

3 个答案:

答案 0 :(得分:1)

你可以试试这个......

func afterServiceStatus(notification : NSNotification) {

            print(notification.userInfo!)
            guard let data =  notification.userInfo!["data"]  else{
                print("data have no idea ")
                return
            }

             let driverId = notification.userInfo![0]?.objectForKey("data")?.valueForKey("driverId") 

                print(driverId)



        }

答案 1 :(得分:0)

您应该尽量避免所有强制解包,因为如果您以意外的格式返回JSON,它们会使您的代码容易崩溃。

这应该从您的字典中检索driverId

func afterServiceStatus(notification: NSNotification) {

  guard
    let userInfo = notification.userInfo as? [String: Any],
    let data = userInfo["data"] as? [[String: Any]],
    let driverId = data[0]["driverId"] as? String
  else {
    return
  }

  print(driverId)
}

答案 2 :(得分:0)

func afterServiceStatus(notification : NSNotification) {

            print(notification.userInfo!)
            guard let data =  notification.userInfo!["data"]  else{
                print("data have no idea ")
                return
            }
if let driverId = notification.userInfo[0]["data"]["driverId"].string
         {
            print(driverId)
         }
}

如果它没有工作然后转发我的链接,我会给你正确的解决方案。