简体   繁体   中英

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)")
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM