我是解析 JSON 的新手。我做了一个单一视图应用程序。我使用此函数从 URL 获取 JSON:
func parseData(){
//created URL
guard let requestURL = URL(string: "https://machla.bh/api-category2") else {return }
//creating URLRequest
var request = URLRequest(url: requestURL)
//setting the method to post
request.httpMethod = "POST"
//creating the post parameter by concatenating the keys and values from text field
var postParameters = ""
postParameters += "key=LpfyirxoNOfP8wPns4nZqTw6DQ4wY A2q6yvpKsof6gkYDTykVXSEonTO2VB HE2zRdqrvsyoyMVyRagWtKAtVuOuNs c7QW5KrgbXS8SqPZ7sIDlPEvhBWyo5 NoObAcor3GlO87nRSaFdxhKDRTiBkK 3pFsTQyffzuBdIBiM8zFra6Yh8NbbC QQaratgFFE2hzLouNEIHq88xaSqum1 C0z7g325i3hixT5oLSo5tvhpvvdTJO WohfqGSakeGz7hsAU"
postParameters += "&path=59"
postParameters += "&language_id=1"
//adding the parameters to request body
request.httpBody = postParameters.data(using: .utf8)
//creating a task to send the post request
let session = URLSession.shared
let task = session.dataTask(with: request) { data, response, error in
guard error == nil else {
print("error is \(error!.localizedDescription)")
return
}
guard let data = data else {
print("No data was returned by the request!")
return
}
// print data from request
let str = String(data: data, encoding: .utf8)!
print(str)
for eachFetechedCountry in str
{
let eachCountry=eachFetechedCountry as! [String:Any]
let category = eachCountry["categories"] as! String
let product=eachCountry["products"] as! String
self.fetchcountry.append(Country(categories: category, products: product))
}
self.countryTableView.reloadData()
}
//executing the task
task.resume()
}
我正在尝试使用上述函数中的以下语句从 JSON 读取类别和产品。这些声明不起作用。如何从 JSON 读取类别和产品?
for eachFetechedCountry in str
{
let eachCountry=eachFetechedCountry as! [String:Any]
let category = eachCountry["categories"] as! String
let product=eachCountry["products"] as! String
self.fetchcountry.append(Country(categories: category, products: product))
}
为了将类别和产品填充到表视图中,我创建了一个名为
Country
: 的类
class Country{
var product:String
var category:String
init(categories :String, products:String)
{
self.category=categories
self.product=products
}
}
为了将类别和产品填充到表格视图中,我编码:
func tableView(_ tableViewr: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = countryTableView.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text=fetchcountry[indexPath.row].category
cell?.detailTextLabel?.text=fetchcountry[indexPath.row].product
return cell!
}
如何将类别和产品填充到表格视图中?
从此链接您可以下载示例项目进行修正?https://drive.google.com/file/d/0B5pNDpbvZ8SnY3RicXpGN1FYbXc/view?usp=sharing
您应该使用 Swift 4 的功能 - 可解码协议。
let task = session.dataTask(with: request) { data, response, error in
guard error == nil else {
print("error is \(error!.localizedDescription)")
return
}
guard let data = data else {
print("No data was returned by the request!")
return
}
do {
let country = try JSONDecoder().decode(Country.self, from: data)
// do what you want here with Country array
// ...
} catch let error {
// catch error and handled it here
}
DispatchQueue.main.async {
self.countryTableView.reloadData()
}
}
//executing the task
task.resume()
始终在主线程中更新表格视图!!!
并使用这些结构:
struct Country: Decodable{
var categories: [Category]
}
struct Category: Decodable {
var name: String
var products: [Product]
}
struct Product: Decodable {
var name: String
}