下面是一般的JSON我看到:解析JSON没有对象名称
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
但我试图解析JSON的格式,没有物体(“雇员”从上面的例子):
[{"id":"1","company":"1","facility":"2","starttime":"1454936400","complete_time":"1454979600","scheduled_hours":"12"},{"id":"3","company":"1","facility":"2","starttime":"1455021660","complete_time":"1455061660","scheduled_hours":"12"}]
下面是我想要使用的代码:
let requestURL: NSURL = NSURL(string: url)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let stations = json[1] as? [[String: AnyObject]] {
print(json)
for station in stations {
if let name = station["company"] as? String {
print(name)
}
}
}
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
但我不能输出任何来自JSON数据的值。我该怎么做?我在Swift和XCode中很新。
或者如果我可以格式化我的数据看起来像第一个JSON,它会好吗?数据从SQL查询中作为数组返回。
更新:当我打印(json [1])时,它只打印第二组。我想我越来越近了。
目前尚不清楚你的意思。你是说你想能够处理没有外部字典的JSON输入,而只是有一个项目数组?你的第二个JSON示例看起来是一个具有完全不同键的字典数组。 –
我的意思是,我如何解析它,而不像第一个示例中的“employees”那样使用外部字典。 –
有一个名为SwiftyJSON的流行库。你可能想看看它。 – Santhosh