2016-12-13 23 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) 
     } 
} 

如果不工作,那么我转发链接,我我会给你适当的解决方案。