这是我看到的常见 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 查询中返回。
更新:当我 print(json[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
}
关于php - 解析没有对象名称的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35705101/