php - 解析没有对象名称的 JSON

标签 php ios json swift

这是我看到的常见 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/

相关文章:

ios - 占位符图像的大小会影响性能吗?

php - Codeigniter - 帖子中的 json 对象数组

php - MySQL 表日期更新给出 00/00/0000 12 :00:00 am format in table

ios - 使用来自原始 PCM 16000 采样率流的 CMSampleTimingInfo、CMSampleBuffer 和 AudioBufferList

php - 在代码中引用 MySQL 表键的最佳方式

ios - 为什么在 heightForRowAt 方法中我的单元格为零?

javascript - 如何用 Greasemonkey 的用户脚本替换 JSON 字符串中的文本

javascript - JSON.stringify 无需转义

php - preg_match 在 anchor 上提取 mailto

php - 认证后的 Laravel 表单提交