Swift-使用JSONDecoder解码JSON数据 [英] Swift - decode JSON data with JSONDecoder
问题描述
我正在使用CocktailDB API,并且遇到了一些问题.
我创建了一个请求,以从特定类别中获取鸡尾酒(每个鸡尾酒的名称和图片).然后,我尝试使用Decodable协议解析JSON.但这不起作用,并显示JSON错误.
I'm working with CocktailDB API and having some problems.
I create a request to get cocktails (each cocktail's name and image) from specific category. Then I try to parse JSON with Decodable protocol. But it doesn't work and JSON Error is displayed.
因此,我想从以下请求中获取鸡尾酒类别"https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list"并为每个类别都有一个小节(标题中显示类别名称),并带有该小节中的鸡尾酒.
Therefore I want to get cocktails categories from the following request "https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list" and have a section for each category (display category name in a header) with the cocktails from this section.
我的饮料型号:
struct Drinks:Decodable {
var drinks: [Drink]
}
struct Drink:Decodable {
var strDrink: String
var strDrinkThumb: String
}
我的类别模型:
struct Categories: Decodable {
var drinks: [Drink]
}
struct Category: Decodable {
var strCategory: String
}
我的代码:
class ViewController: UIViewController {
var drinks = [Drinks]()
var categories = [Categories]()
override func viewDidLoad() {
super.viewDidLoad()
downloadJSON()
}
func downloadJSON() {
let category = "Cocoa" // for example
let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=\(category)")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.drinks = try JSONDecoder().decode([Drinks].self, from: data!)
print(self.drinks)
} catch {
print("JSON Error")
}
}
}.resume()
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return drinks.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return ""
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell(style: .default, reuseIdentifier: "cell")
}
}
JSON结构:
推荐答案
您需要在此处进行一些其他更改.一种将解码更改为Drinks.self
.然后重新加载tableView
.并返回该节标题的字符串.这是代码:
You need to make a few additional changes here. One change the decoding to Drinks.self
. Then reload the tableView
. And return the String for the section header. Here's the code:
解码:
var drinks = [Drink]() // modify the drinks property
if let data == data {
do {
self.drinks = try JSONDecoder().decode(Drinks.self, from: data).drinks
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
和titleForHeaderInSection方法:
And titleForHeaderInSection method:
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return drinks[section].strDrink
}
这篇关于Swift-使用JSONDecoder解码JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!