【发布时间】:2017-07-07 08:29:20
【问题描述】:
我在 swift (php 连接) 中加载 JSON 结果时遇到问题。
我可以检索 JSON 数据,但它不允许我将其分配给变量。
它总是将结果分配为Optional。
JSON 数据:
{
"country": [{
"id": 1,
"name": "Australia",
"code": 61
}, {
"id": 2,
"name": "New Zealand",
"code": 64
}]
}
xCode 输出:
["country": <__NSArrayI 0x60000002da20>(
{
code = 61;
id = 1;
name = Australia;
},
{
code = 64;
id = 2;
name = "New Zealand";
}
)
]
Country Name: Optional(Australia)
Country Name: Optional(New Zealand)
.swift 文件:
//function did_load
override func viewDidLoad() {
super.viewDidLoad()
//created RequestURL
let requestURL = URL(string: get_codes)
//creating NSMutable
let request = NSMutableURLRequest(url: requestURL!)
//setting the method to GET
request.httpMethod = "GET"
//create a task to get results
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil{
print("error is \(String(describing: error))")
return;
}
//lets parse the response
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
print(json)
if let countries = json["country"] as? [[String: AnyObject]] {
for country in countries {
print("Country Name: \(String(describing: country["name"]))")
print("Country Code: \(String(describing: country["code"]))")
if let couname = country["name"] as? [AnyObject] {
print(couname)
}
if let coucode = country["code"] as? [AnyObject] {
print(coucode)
}
}
}
} catch {
print("Error Serializing JSON: \(error)")
}
}
//executing the task
task.resume()
}
【问题讨论】:
-
字典下标返回一个可选值,例如参见stackoverflow.com/questions/25979969/…(或 Swift 语言参考)。
country["name"] as? [AnyObject]没有意义,因为该值是字符串,而不是数组。 -
请注意,
String(describing:)几乎从不您想要什么,并隐藏了实际的类型问题。 -
@RAJAMOHAN-S:反引号用于
code,不是一般强调。没有理由将“JSON”格式化为JSON或将“变量”格式化为variable。 -
@MartinR,好的,谢谢兄弟 :) 我注意到了。