我有一个从Web php文件中获取JSON数据的代码,数据使用contentOfUrl
转到data
var,然后转换为jsonarray
var使用 NSJSONSerialization.JSONObjectWithData
输入 AnyObject。
但问题是,当我想从 jsonarray
var 中使用它时,我搜索了两天,找到了一个,但没有工作,因为他的 AnyObject var 结构不同。
那么我该如何使用它呢?
代码:
import Foundation
class DBConnectController{
func ViewControllerConnect(DeviceID : Int) -> String{
let data : NSData = NSData(contentsOfURL : NSURL(string: "http://xx.com/xc.php")!)!
var jsonarray : AnyObject
do {
jsonarray = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
print(jsonarray["2"]) // tried this but didn't work
print(jsonarray["2"].value) // tried this but didn't work
// and tried other
} catch {
print("Error decoding json using NSJSONSerialization.JSONObjectWithData")
}
return "f"
}
}
最佳答案
你拥有的是一个字典对象数组。 (顺便说一句,我使用的是 Xcode 6/Swift 1.2,因此您可能不需要“err”参数。)
(顺便说一句,您的数组似乎只有一个元素,因此请在超出它之前检查:myStructuredData.count
。)
func viewControllerConnect(deviceID: Int) -> String? {
var err: NSError?
var retVal: String?
if let url = NSURL(string: "http://xx.com/xc.php"),
data = NSData(contentsOfURL: url), // BAD You're doing long-running network task in UI thread, address this soon
jsonData: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: &err) {
if let myStructuredData = jsonData as? [[String: AnyObject]] { // You have an array of dictionaries there
retVal = myStructuredData[0]["status"] as? String // For example, not sure of your exact needs & conventions
}
else {
println("JSON data had unexpected structure: \(err?.localizedDescription)")
}
}
else {
println("Could not load JSON data")
}
return retVal
}
关于swift - 在 AnyObject Swift 2.0 中使用数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31800830/