簡體   English   中英

在swift3中保存時如何獲取nil JSON數據?

[英]How to obtain the JSON data as nil when saving in 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)
}

假設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是無意義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM