[英]xCode, Swift 3.0 JSON parse string response
I'm trying to get the status code and put it in an if statement.我正在尝试获取状态代码并将其放入 if 语句中。 This code will run in the Xcode playground.此代码将在 Xcode Playground 中运行。
Right now status returns as ["200"] with square brackets around it.现在状态返回为["200"]并用方括号括起来。 If I remove the brackets it returns as nil .如果我删除括号,它会返回nil 。
How do I return status as 200 and put it in an if statement?如何将状态返回为200并将其放入 if 语句中?
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\\"
您忘记了\\"status\\"
”后的“ : \\"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编辑:见下面OP的评论
It returns ["status"] and that's perfectly normal because your json
object is an Array
of String
( [String]
).它返回["status"] ,这是完全正常的,因为您的json
对象是一个String
Array
( [String]
)。 To get 200
you have to fetch the first object of this array :要获得200
您必须获取此数组的第一个对象:
if let array = json["status"] as? [String]
{
let code = array.first // Here, code should be 200
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.