Swift 4

时间:2018-04-18 13:07:52

标签: json swift4 decodable

在@matt的帮助下。我能够解决它,并且完成的代码在下面适用于在不久的将来会遇到similer问题的人。 鉴于以下JSON

{
    "restaurants": [
        {
            "id": 1,
            "restaurantName": "Chuks",
            "restaurantPicture": "restaurantImages/benards.jpg",
            "status": "Working",
            "workingDays": "Tuesday to Sunday",
            "workingHours": "3pm to 10pm"
        },
        {
            "id": 3,
            "restaurantName": "Chuks",
            "restaurantPicture": "restaurantImages/benards.jpg",
            "status": "Working",
            "workingDays": "Tuesday to Sunday",
            "workingHours": "3pm to 10pm"
        },
        {
            "id": 4,
            "restaurantName": "Chuks",
            "restaurantPicture": "restaurantImages/benards.jpg",
            "status": "Working",
            "workingDays": "Tuesday to Sunday",
            "workingHours": "3pm to 10pm"
        },
        {
            "id": 5,
            "restaurantName": "Chuks",
            "restaurantPicture": "restaurantImages/benards.jpg",
            "status": "Working",
            "workingDays": "Tuesday to Sunday",
            "workingHours": "3pm to 10pm"
        },
        {
            "id": 6,
            "restaurantName": "Chuks",
            "restaurantPicture": "restaurantImages/benards.jpg",
            "status": "Working",
            "workingDays": "Tuesday to Sunday",
            "workingHours": "3pm to 10pm"
        }
    ]
}

我正在尝试使用此代码访问Dictionary中的数组到表中。所以我做了一个结构。以下是我的Structfile的内容。

    struct Response: Codable {

    let restaurants: [Restaurant]

    struct Restaurant: Codable {
        let id: Int
        let restaurantName: String
        let restaurantPicture: String
        let status: String
        let workingDays: String
        let workingHours: String
    }
}

这是我的主要视图控制器

        import UIKit

    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


        @IBOutlet weak var tabelView: UITableView!

        var restaurants = [Response]()

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.

            downloadJSON {
                self.tabelView.reloadData()
            }

            tabelView.delegate = self
            tabelView.dataSource = self

        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return restaurants.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = UITableViewCell(style: .default, reuseIdentifier: nil)

            cell.textLabel?.text = restaurants[indexPath.row].restaurantName.capitalized

            return cell
        }


        func downloadJSON(completed: @escaping ()->()){

            let url = URL(string: "http://localhost:8888/tableview/tableView.php")

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

                if error == nil{
                    do{
                        let downloadedRestaurants = try JSONDecoder().decode(Response.self, from: data!)
        print(downloadedRestaurants.restaurants.map{$0.restaurantName})

        self.restaurant.append(downloadedRestaurants)


                        DispatchQueue.main.async {
                            completed()
                        }
                    }catch{
                        print(error)
                    }
                }
            }.resume()

        }
    }

谢谢@matt。我希望这篇文章对其他新手或有类似问题的人都有用 干杯!

1 个答案:

答案 0 :(得分:3)

问题是您尝试解码为"restaurants"。但看看你的JSON!它不是一系列的RestaurantStats。它根本不是一个数组。它是一个包含单个键SSLHandshakeException的字典。您需要创建那个结构并解码为

编辑由于我给出了答案,您修改了代码以声明外部结构响应。这是正确的 - 这正是我说你应该做的。所以解码为响应,你就完全了。