【问题标题】:having difficulty fetching JSON Dictionary难以获取 JSON 字典
【发布时间】:2016-11-07 06:47:34
【问题描述】:

我从 API 得到的回应是

 items are.....****************** ("user_img",     http://www.xxx/Content/Images/Products/NoImageAvailable.jpg)
  items are.....****************** ("user_posts", 10)
  items are.....****************** ("5", {
  "post_id" : 135,
  "post_img" : [
    {
   "guid" : "http:\/\/www.xxx\/wp-     content\/uploads\/2016\/10\/IMG_1477393867.jpg"
  }
]
})
items are.....****************** ("9", {
"post_id" : 143,
"post_img" : [
  {
    "guid" : "http:\/\/www.xxx\/wp-content\/uploads\/2016\/10\/IMG_1477453054.jpg"
}
]
})
items are.....****************** ("2", {
"post_id" : 129,
"post_img" : [
   {
    "guid" : "http:\/\/www.xxx\/wp-  content\/uploads\/2016\/10\/IMG_1477280037.jpg"
  }
  ]
 })
items are.....****************** ("1", {
 "post_id" : 112,
 "post_img" : [
   {
    "guid" : "http:\/\/www.xxx\/wp-content\/uploads\/2016\/10\/IMG_1475494067.jpg"
}
 ]
})
items are.....****************** ("8", {
 "post_id" : 141,
 "post_img" : [
  {
  "guid" : "http:\/\/www.xxx\/wp-   content\/uploads\/2016\/10\/IMG_1477452361.jpg"
    }
      ]
})

我调用它的函数

 func getJSON(){

    let getEndPoint: String = "http://xxx/api/get_user_profile_info/"
    Alamofire.request(getEndPoint)
        .responseJSON { response in

            guard response.result.error == nil else {
                // got an error in getting the data, need to handle it
                print("error calling GET")
                print(response.result.error!)
                return
            }

            if let value = response.result.value {

                let json = JSON(value)
               // print(jsonM)
                //print("message are***********************************************")
                //print(json["message"].dictionary)
                let message = json["message"].dictionary

                for items in message! {

                    print("items are.....******************", items)


                }


                 //DispatchQueue.main.async {
                // self.afData = 1
               // self.tableView.reloadData()

            }
    }

}

模型类

class ProfileJSON {

    var user_Image: URL?
    var post_image:URL?


    init(items: JSON) {

        self.user_Image = items["user_img"].URL

        let post_imgAA = items["post_img"].array
        for itemsIMG in post_imgAA! {
            self.post_image = itemsIMG["guid"].URL
        }
    }

}

我想让 user_img 显示为个人资料图片和 post_img 用于在 CollectionViewCell 中显示图片。发现很难将 JSON Dictionary 转换为 Swift MutableObject 。任何建议,任何教程链接都会对我有很大帮助。从这个月开始,我才开始使用 JSON,觉得很困难。

【问题讨论】:

    标签: json swift dictionary swift3 alamofire


    【解决方案1】:

    在您的ProfileJSON 中,您需要为post_image 创建URL 类型的数组,因为user_Image 是一次但post_image 会多次出现,然后您可以像这样从字典中获取post_image

    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))
                        }
                    }
                }
            }
        }        
    }
    

    现在像这样在message 初始化之后创建ProfileJSON 的对象。

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

    【讨论】:

    • 我需要一些时间来消化哈哈,但非常感谢您的帮助。你是个传奇。
    • @ArafinMacRussell 欢迎朋友:)
    【解决方案2】:

    您可以使用 DicitonaryObject.objectForKey("KEYNAME") 从字典中提取详细信息吗?数据类型 。 数据类型将是存储在该键中的值。 将它存储在一个变量中,然后在任何你想要的地方使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      相关资源
      最近更新 更多