2017-01-25 17 views
0

代碼:如何在swift3中保存JSON數據爲零?

var json: AnyObject? 
do { 
    json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any] as AnyObject? 
    let UserID = json?["UserID"] as? [String:AnyObject] 
    print(UserID) //printing nil 

} 
catch { 
    print(error) 
} 

回答

0

假設JSON的根對象是字典和用於userID字符串的值可能是

do { 
    if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any] { 
     if let userID = json["UserID"] as? String { // or as? Int if the user id is an integer 
      print(userID) 
     } 
    } 
} 
catch { 
    print(error) 
} 

.allowFragments是如果根對象被認爲無義是一個集合類型。