在Swift中从数组中获取项目

时间:2017-11-24 01:36:06

标签: json swift

我对Swift很新,并且花了几个小时试图从JSON响应中提取photo_url密钥。

我正在使用它来阅读JSON:

let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)

然后:

                if let eventsDictionary = jsonDictionary {
                    let upcomingEvents = UpcomingEvents(eventsDictionary: eventsDictionary)
                    completion(upcomingEvents)
                } else {
                    completion(nil)
                }

这是我(失败)尝试拔出钥匙:

init(eventsDictionary: [String : Any]) {
    //photoUrl = eventsDictionary[EventKeys.photoUrl] as? String
    let groups: NSArray = eventsDictionary["groups"] as! NSArray
    let url: String = groups[0]
   print("THIS IS YOUR RETURNED PHOTO URL--\(url)--END OF RETURNED PHOTO URL")
}

enter image description here

我将“[String:Any]”更改为[String:AnyObject],现在我得到了这个...... enter image description here

4 个答案:

答案 0 :(得分:2)

向NSArray投射Any会有问题。只需使用[String:AnyObject]使您的Init方法。但是,最好在这里使用Array而不是NSArray

答案 1 :(得分:0)

尝试使用以下代码获取网址。

let firstObj  = groups[0] as! [String: String] // use if let to unwrap is better
let url = firstObj["photo_url"]

答案 2 :(得分:0)

要从照片中的json文件中获取“photo_url”,

它看起来像这样:

init(eventsDictionary: [String : Any]) {
   if let groups = eventsDictionary["groups"] as? [NSDictionary]{
        /*
        // Get All URL
        var urls : [String] = []
        for group in groups{
            if let url = group.value(forKey: "photo_url"){
                urls.append(url)
            }
        }
        */

        // Groups[0] url
        let url: String = groups[0].value(forKey: "photo_url") as! String
        print("THIS IS YOUR RETURNED PHOTO URL--\(url)--END OF RETURNED PHOTO URL")
    }
}

答案 3 :(得分:0)

你需要把json读作`[String:Any]。

 if let eventsDictionary = json as? [String: Any] {
     let upcomingEvents = UpcomingEvents(eventsDictionary: eventsDictionary)
     completion(upcomingEvents)               
 }

然后,像这样初始化您的UpcomingEvents模型

init(eventsDictionary: [String : Any]) {
    let groups: NSArray = eventsDictionary["groups"] as! NSArray
    let group1 = groups[0] as! NSDictionary
    let photoURL = group1["photo_url"] as! String
    print(photoURL)
}