c.davies c.davies - 1 month ago 13
JSON Question

xCode, Swift 3.0 JSON parse string response

I'm trying to get the status code and put it in an if statement. This code will run in the Xcode playground.

Right now status returns as ["200"] with square brackets around it. If I remove the brackets it returns as nil.

How do I return status as 200 and put it in an if statement?

import Foundation

let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"],\"status\":[\"200\"],\"message\":\"User has been created\",\"id\":null,\"username\":\"asdf\"}"//"{\"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]
let status = json["status"] as? [String]

} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}

Answer

You forgot a ":" after \"status\"

let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"],\"status\":[\"200\"],\"message\":\"User has been  created\",\"id\":null,\"username\":\"asdf\"}"//"{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"

EDIT : see comment of OP below

It returns ["status"] and that's perfectly normal because your json object is an Array of String ( [String] ). To get 200 you have to fetch the first object of this array :

if let array = json["status"] as? [String]
{
   let code = array.first // Here, code should be 200
}
Comments