Correctly Parsing JSON in Swift 3

前端 未结 9 958
甜味超标
甜味超标 2020-11-21 07:00

I\'m trying to fetch a JSON response and store the results in a variable. I\'ve had versions of this code work in previous releases of Swift, until the GM version of Xcode 8

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 07:52

    let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
    
    let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
    
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
        if let names = json["names"] as? [String] 
    {
            print(names)
    }
    } catch let error as NSError {
        print("Failed to load: \(error.localizedDescription)")
    }
    

提交回复
热议问题