在swift3中保存时,如何将JSON数据获取为nil?
代码:在swift3中保存时,如何将JSON数据获取为nil?,json,swift3,Json,Swift3,代码: 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 { pr
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)
}
假设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
是无意义的