Исправить 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)
}