swift3 - Parsing JSON using Swift 3 -
i have json data want consume in swift 3. i'm learning swift , building basic app displays list of items in tableuiview json.
{ "expertpainpanels" : [ { "name": "user a", "organization": "company a" }, { "name": "user b", "organization": "company b" } ] }
i'm trying data using swift 3.
if (statuscode == 200) { do{ let json = try? jsonserialization.jsonobject(with: data!, options:.allowfragments) // [[string:anyobject]] /* if this: let json = try? jsonserialization.jsonobject(with: data!, options:.allowfragments) as! [string:any] if let experts = json?["expertpainpanels"] as! [string: any] { "initializer conditional binding must have optional type, not '[string: any]'" */ // type 'any' has no subscript members. if let experts = json["expertpainpanels"] as? [string: anyobject] { expert in experts { let name = expert["name"] as? string let organization = expert["organization"] as? string let expertpainpanel = expertpainpanel(name: name, organization: organization)! self.expertpainpanels += [expertpainpanel] self.tableview.reloaddata() self.removeloadingscreen() } } }catch { print("error json: \(error)") } }
it working fine in swift 2. updated swift 3 broke code. read several so, still have hard time understanding it. applied suggestions including json parsing in swift 3, i'm still unable fix error i'm getting.
as of swift 3, need cast on.
this line:
let json = try? jsonserialization.jsonobject(with: data!, options:.allowfragments)
should become this:
let json = try jsonserialization.jsonobject(with: data!, options:.allowfragments) as? [string : anyobject]
this because jsonserialization returns any
, not implement variation []
operator. make sure safely unwrap cast , take common measures ensure don't crash program.
edit: code should more or less this.
let data = data() let json = try jsonserialization.jsonobject(with: data, options:.allowfragments) as! [string : anyobject] if let experts = json["expertpainpanels"] as? [string: anyobject] {
Comments
Post a Comment