如何在swift3中保存时将JSON数据获取为nil?

时间:2017-01-25 07:10:57

标签: 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 {
    print(error)
}

1 个答案:

答案 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是无意义的。