解析使用API​​获取的Json后,无法将其分配给Swift中的变量

时间:2018-08-20 06:47:58

标签: ios json iphone swift4

我使用swift4创建一个iOS应用

我遇到一个问题。 解析使用API​​获取的Json后,无法将其分配给var stores : [categories.stores]?。打印值为

但是打印let json = try decoder.decode(categories.self, from: data),我可以获得Json数据。

并且没有错误。所以我不知道为什么我不能替代

请帮助我。

StoreListViewController

class StoreListViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var TableView: UITableView!


var category_id = ""
let cellReuseIdentifier = "cell"
// use json 
var stores : [categories.stores]?

override func viewDidLoad() {
    super.viewDidLoad()
    TableView.delegate = self
    TableView.dataSource = self

    let url = URL(string: "http://127.0.0.1:8000/search/api/category?category_id=" + category_id)
    let request = URLRequest(url: url!)
    let session = URLSession.shared

    let encoder: JSONEncoder = JSONEncoder()
    encoder.dateEncodingStrategy = .iso8601
    encoder.outputFormatting = .prettyPrinted

    session.dataTask(with: request){(data, response, error)in if error == nil,
        let data = data,
        let response = response as? HTTPURLResponse{

        let decoder: JSONDecoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        do {

            let json = try decoder.decode(categories.self, from: data)

            // in to stores variable
            self.stores = json.stores

            DispatchQueue.main.async {
                self.TableView.reloadData()
            }
        } catch {
            print("error:", error.localizedDescription)

        }

        }

        }.resume()

    print(stores as Any)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}


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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as? TableViewCell
        else {
            fatalError("The dequeued cell is not an instance of TableViewCell.")
    }

    cell.storeName.text! = stores![indexPath.row].name
    cell.storeLocation.text! = stores![indexPath.row].location


return cell
}

}

数据模型

struct categories : Codable {
let id : Int
let name : String
let stores : [stores]

struct stores : Codable {
    let id : Int
    let name : String
    let location : String
    let price : String
    let open_time : String
    let closed_day : String
    let photos : [photos]
    let tags : [tags]

    struct photos:Codable {
        let id : Int
        let path : String
    }

    struct tags:Codable {
        let id : Int
        let name : String
    }
}
}

1 个答案:

答案 0 :(得分:-1)

我在关闭之前正在工作。