使用JSONPlaceholder进行JSON解析Swift

时间:2019-02-21 18:57:59

标签: ios json swift json-serialization

我正在使用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

1 个答案:

答案 0 :(得分:1)

Okey,因此使用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