我的场景,在我的项目中,我在struct的帮助下获得JSON
数据。在这里,我可以获取所有JSON
数据。现在,我需要在multiple
中加载每个索引array
的值,并将其加载到tableview
中。
注意:我也有搜索栏-按名称搜索
我的JSON
{
"status": 1,
"status_code": 200,
"message": “name list",
"result": [
{
"id": 6,
"name": "Afrikaans",
"image": "https://www.google.com/",
"code": "af",
“mob_code": null
},
{
"id": 8,
"name": "Albanian",
"image": "https://www.google.com/",
"code": "sq",
“mob_code": null
}
]
}
我的代码
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
if let error = error {
print("returning error", error);
return
}
do {
let result = try JSONDecoder().decode(LanguagesData.self, from:data!)
//print("RESPONSE:\(result)")
} catch {
print(error)
}
})
task.resume()
答案 0 :(得分:1)
更正json
{
"status": 1,
"status_code": 200,
"message": "name list",
"result": [{
"id": 6,
"name": "Afrikaans",
"image": "https://www.google.com/",
"code": "af",
"mob_code": null
},
{
"id": 8,
"name": "Albanian",
"image": "https://www.google.com/",
"code": "sq",
"mob_code": null
}
]
}
创建实例变量
var arr = [Inner]()
解码
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let res = try decoder.decode(Root.self,from:data)
arr = res.result
DispatchQueue.main.async {
self.tableView.reloadData()
}
模型
struct Root: Codable {
let status, statusCode: Int
let message: String
let result: [Inner]
}
struct Inner: Codable {
let id: Int
let name: String
let image: URL
let code: String
let mobCode: String?
}
表数据源和委托
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! <#CellName#>
let item = arr[indexPath.row]
cell.student_label.text = item.name
cell.photo.sd_setImage(with:item.image, placeholderImage: UIImage(named: "placeholder.png"))
}
测试:
let str = """
{
"status": 1,
"status_code": 200,
"message": "name list",
"result": [{
"id": 6,
"name": "Afrikaans",
"image": "https://www.google.com/",
"code": "af",
"mob_code": null
},
{
"id": 8,
"name": "Albanian",
"image": "https://www.google.com/",
"code": "sq",
"mob_code": null
}
]
}
"""
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let res = try decoder.decode(Root.self,from:Data(str.utf8))
print(res)
}
catch {
print(error)
}