简体   繁体   中英

xcode swift 3.0 parse JSON 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 to 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 can try this workaround:

let responseString = Optional("{\"status\":\"200\",\"message\":\"User has been created\",\"id\":null,\"username\":\"asdf\"}")
let responseData = responseString?.data(using: .utf8)
let dict: Dictionary<String, Any> = try JSONSerialization.jsonObject(with: responseData!, options: []) as! Dictionary<String, Any>

let status = dict["status"] // optional value stored with "status" key in Dictionary

It seems that actually, Swift 3 refuses to compile using:

let dict: Dictionary<String, Any> = try JSONSerialization.jsonObject(with: responseString?.data(using: .utf8)!, options: []) as! Dictionary<String, Any>

Swift 3 claims that responseString?.data(using: .utf8)! should be unwrapped although it is already.

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: .utf8)

do {
    let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
    let status = json["status"] as? [String]
    let yourValue =  status?[0]

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

I just add ( : ) after status in json formate to be invalid

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