这是我看到的通常的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])时,它只打印第二组。我想我越来越近了。
答案 0 :(得分:1)
NSJSONSerialization.JSONObjectWithData
可能很棘手,因为它可以返回Array
又名[AnyObject]
或Dictionary
又名[String: AnyObject]
。
然后你必须测试结果是什么:
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let json = jsonData as? [[String: AnyObject]] {
// json starts with an array
for value in json {
// loop through array
}
} else if let json = jsonData as? [String: AnyObject] {
// json starts with a key
for (key, value) in json {
// loop through dictionary key/values
}
} else {
// This json is broken
}
答案 1 :(得分:0)
1 - 检查statusCode条件是否为真(200或“200”?)
尝试捕获之前的2个打印数据
if (statusCode == 200) {
print(data)
do{
......
}
3-打印json对象
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print(json)
和
4-check json [1]与[[String:AnyObject]]
相同