having difficulty fetching JSON Dictionary

孤者浪人 提交于 2019-12-02 09:22:14

In your ProfileJSON you need to create array of URL type for post_image because user_Image is once but post_image is coming multiple times and then you can get post_image from dictionary like this.

class ProfileJSON {

    var user_Image: URL?
    var post_image: [URL?] = [URL?]()

    init(dic: [String: Any]) {
        if let userUrl = dic["user_img"] as? String {
            self.user_Image = URL(string: userUrl)
        }

        //For getting only number keys with ascending order
        let keys = (Array(dic.keys) as [String]).filter { (Int($0) != nil) }.sorted {
            (s1, s2) -> Bool in return s1.localizedStandardCompare(s2) == .orderedAscending
        }

        //Loop through the keys Array and append all your `post_image`.
        for key in keys {                
            if let innerDic = dic[key] as? [String: Any], 
            let post_imgArray = innerDic["post_img"] as? [[String: Any]] {
                for post in post_imgArray {
                    if let postUrl = post["guid"] as? String {
                        self.post_image.append(URL(string: postUrl))
                    }
                }
            }
        }
    }        
}

Now create the object of ProfileJSON after initialization of message like this.

if let message = json["message"] as? [String: Any] {
     let profileJSON = ProfileJSON(dic: message)
}

You can extract details from dictionary using DicitonaryObject.objectForKey("KEYNAME") as? Datatype . Datatype would the of the value stored in that key. Store it in a variable and use it wherever you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!