Swiftyjson: Parse json array in swift 3

Created on 17 Nov 2016  路  5Comments  路  Source: SwiftyJSON/SwiftyJSON

Hi.
I have a json:

{
"code":1,
"message":"success",
"data":[
{
"fullName":"John",
"gender":"male",
"age":20
},
{
"fullName":"Kane",
"gender":"male",
"age":22
},
{
"fullName":"Kane",
"gender":"male",
"age":22
}
]
}

To get data json, in swift 2.3, i used:

if let dataJson: JSON = json["data"] {
            for (_, subJson) : (String, JSON) in dataJson {
                let fullName = subJson["fullName"].string
                let gender = subJson["gender"].string
                let age = subJson["age"].int
                // do something
            }
        }

But in swift 3, i get an error at: json["data"]
image

Please help me.
Thank you!

Most helpful comment

  let json = JSON(data: data!)
  let dataJson = json["data"]

  for subJson in dataJson.arrayValue {
        let fullName = subJson["fullName"].string
         let gender = subJson["gender"].string
         let age = subJson["age"].int
            // do something
   }

All 5 comments

json["data"] returns a value of type JSON which is a non optional, you can't use it in an if let unwrapping pattern. I would remove the if check altogether.

should i do ?
Please.
P/s: Those code worked fine on swift 2.3

  let json = JSON(data: data!)
  let dataJson = json["data"]

  for subJson in dataJson.arrayValue {
        let fullName = subJson["fullName"].string
         let gender = subJson["gender"].string
         let age = subJson["age"].int
            // do something
   }

Thanks you very much 馃憤

Looks like your issue is addressed, closing now. Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ejpusa picture ejpusa  路  5Comments

donadley picture donadley  路  4Comments

richburdon picture richburdon  路  3Comments

patchthecode picture patchthecode  路  3Comments

joernroeder picture joernroeder  路  4Comments