2016-12-13 22 views
0

分析數據我無法獲得driverId從這個JSON如何從JSON數組

[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) 
    //  } 


    } 
+0

改變你的條件,這一個,如果讓driverId =數據![0]![ 「driverId」] { 打印(driverId) } –

+0

你應該swiftyJSON看一看擺脫這種「! '瘋狂 – HaneTV

+0

@SapanaRanipa強制刪除'!'後的數據然後運行時錯指令錯誤trowing –

回答

3

你可以試試這個...

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) 



     } 
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) 
} 
+0

'[NSObject:AnyObject]?'不能轉換爲'[String:Any]' –

+0

定義與以前的值衝突 –

2
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) 
     } 
} 

如果不工作,那麼我轉發鏈接,我我會給你適當的解決方案。