Swift 4 中的可编码 JSON 字典

Encodable JSON dictionary in Swift 4

在@matt 的帮助下。我能够解决它,下面是完成的代码,供任何在不久的将来遇到类似问题的人使用。 鉴于以下 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"
        }
    ]
}

我正在尝试使用此代码访问字典中的数组 table。所以我做了一个结构。以下是我的 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{[=14=].restaurantName})

        self.restaurant.append(downloadedRestaurants)


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

        }
    }

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

问题是您正在尝试解码为 [RestaurantStats]。但是看看你的JSON!它不是一组 RestaurantStats。它根本不是一个数组。它是一个只有一个键的字典,"restaurants"。您需要创建 that 结构并解码为 that.

编辑 自从我给出答案后,您已修改代码以声明外部结构响应。这是正确的——这正是我所说的你应该做的。所以解码为 Response 就大功告成了。