代码:
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 :(得分: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
是无意义的。