【问题标题】:JSON Parsing Swift using JSONPlaceholder使用 JSONPlaceholder 解析 Swift 的 JSON
【发布时间】:2019-02-21 18:57:59
【问题描述】:

我正在使用 Swift 和 JSONPlaceholder。我要检索包含在:https://jsonplaceholder.typicode.com/photos

中的所有数据

我创建了一个加入 url 的函数,下载 JSON,但是我不知道如何获取标题和 thumbnailUrl 以传递然后填充 tableView。过去我使用过这段代码,但现在它不起作用,因为在 JSONPlaceholder 上没有数组。

对重新排列代码以读取和获取 jsonplaceholder 元素有什么帮助吗?

func loadList(){

    let url = URL(string: urlReceived)

    var myNews = NewInfo()

    let task = URLSession.shared.dataTask(with: url!) {
        (data, response, error) in

        if error != nil{
            print("ERROR")
        }
        else{
            do {
                if let content = data{
                    let myJson = try JSONSerialization.jsonObject(with: content, options: .mutableContainers)

                    //print(myJson)
                    if let jsonData = myJson as? [String : Any] {

                        if let myResults = jsonData["list"] as? [[String : Any]]{
                            //dump(myResults)

                            for value in myResults{
                                //Read time string from root
                                if let time = value ["dt_txt"] as? String{

                                    myNews.time = time
                                }
                                //Read main container
                                if let main = value["main"]
                                    as? [String : Any]{
                                    if let temperature = main["temp"] as? Double {
                                        myNews.temperature = String(temperature)
                                    }
                                }
                                //Read from weather container
                                if let weather = value["weather"] as? [[String: Any]]{
                                    for value in weather{
                                        if let weatherContent = value["description"] as? String{
                                            myNews.weatherDescription = weatherContent
                                        }
                                    }
                                }


                                self.myTableViewDataSource.append(myNews)

                            }
                            dump(self.myTableViewDataSource)

                            DispatchQueue.main.async {
                                self.tableView.reloadData()
                            }

                        }

                    }
                }
            }
            catch{

            }
        }
    }
    task.resume()
}//End func

【问题讨论】:

  • 我知道,这不是您问题的答案,但是您是否尝试使用 swiftyJSON 库?它易于使用,易于理解。
  • 其实没有???你认为它可以解决我的问题吗?
  • 使用 Alamofire 和 SwiftyJSON 库,您可以编写非常简洁易读的代码,例如:imgur.com/a/xvzqoO6。如果你 print(json),你可以看到结构,你可以使用 .arrayValue 或 .dictionaryValue。
  • 我已经导入了 Alamofire...我需要尝试使用 SwiftyJSON
  • 我想它会对你有所帮助 :) 请告诉我 :)

标签: ios json swift json-serialization


【解决方案1】:

好的,所以使用 Alamofire + SwiftyJSON,您可以这样做:

func loadList(){

    let url = "https://jsonplaceholder.typicode.com/photos"
    AF.request(url).responseJSON { (response) in
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            print(json)

            for value in json.arrayValue {
                let url = value.dictionaryValue["url"]!.stringValue
                let albumId = value.dictionaryValue["albumId"]!.stringValue
                let thumbnailUrl = value.dictionaryValue["thumbnailUrl"]!.stringValue
                let id = value.dictionaryValue["id"]!.stringValue
                let title = value.dictionaryValue["title"]!.stringValue

                // Add this album to array.
                let album = AlbumModel(id: id, albumId: albumId, title: title, thumbnailUrl: thumbnailUrl)
                albums.append(album)

            }
        case .failure(let error):
            print(error)
        }

    }
}

编辑:

我为价值观做了模型

class AlbumModel {

var id: String?
var albumId: String?
var title: String?
var thumbnailUrl: String?

init(id: String?, albumId: String?, title: String?, thumbnailUrl: String?){

    self.id = id
    self.albumId = albumId
    self.title = title
    self.thumbnailUrl = thumbnailUrl

   }
}

之后,只需创建一个类似var albums = [AlbumModel]() 的数组,您就可以将所有专辑附加到该数组中。在 tableViewcell 后易于使用(例如:albums[indexPath.row].id

【讨论】:

  • 非常感谢您的回复!但是什么是 AlbumMode?​​span>
  • 这真是太棒了!非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多