sulabh sulabh - 6 months ago 78
Swift Question

JSON Parsing issue in swift 3 from Array to dictionary

i have a JSON as:

{
"jsonData": {
"userDetails": [
{
"user_id": "a",
"first_name": "First1",
"last_name": "Last1",
"donation_amount": 841,
"donation_time": 1452678347523
},
{
"user_id": "b",
"first_name": "First2",
"last_name": "Last2",
"donation_amount": 841,
"donation_time": 1452678347523
},
{
"user_id": "c",
"first_name": "First3",
"last_name": "Last3",
"donation_amount": 841,
"donation_time": 1452678347523
}
]
},
"total_count": 3
}


and i am parsing in swift using swiftlyJSON : my code is below

private func processProjectDonorsResponse(response: JSON) {
//add to dictionary
let jsonObject = response.dictionaryObject!["jsonData"]! as AnyObject
let details = jsonObject["userDetails"] as! [AnyObject]
var tempModel = [UserModel]()
for detail in details {
let user = UserModel(response: detail as! [String: AnyObject])
tempModel.append(user)
}
}


it was working fine in swift 2 , but now i have upgraded to swift 3 i am getting warning at line
//let details = jsonObject["userDetails"] as! [AnyObject]

as: Cast from String ?! to unrelated type '[AnyObject]' always fail., and gets crashed.
how to fix this problem?

Answer

You can try this

private func processProjectDonorsResponse(response: JSON) {
     //add  to  dictionary
        let jsonObject = response.dictionaryObject!["jsonData"]! as! [String : AnyObject] //Fixed here also
        let details = jsonObject["userDetails"] as! [NSDictionary]
        var tempModel = [UserModel]()
        for detail in details {
          let user = UserModel(response: donor as! [String: AnyObject])
          tempModel.append(user)
        }
}

I must say but i din get the usage of detail variable in for loop :)