ios - JSON 解析 Swift 使用 JSONPlaceholder

标签 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

最佳答案

好的,所以使用 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)
        }

    }
}

编辑:

我为值(value)观做了模型

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)

关于ios - JSON 解析 Swift 使用 JSONPlaceholder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54814326/

相关文章:

ios - 如何使 UICollectionViewFlowLayout itemSize 动态显示屏幕大小

Object Segue 上的 IOS 无法识别选择器

python - instagram.bind.InstagramClientError : Unable to parse response, 无效的 JSON

javascript - 分隔 JSON 对象的值

javascript - 无法使用 JSON 将对象列表传递到 View

swift - 按下按钮时如何在标签之间随机化?

ios - 如何在框架(Objective-C)中将类访问器设为私有(private)

ios - 将数据库保存在 AppGroup 的共享容器中是一种好方法吗

swift - 如何让相机移动得更频繁?

ios - 创建类似于 Facebook News Feed 的 UI 的建议方法是什么?