У меня есть JSON (пока что локальный), который я хочу проанализировать, чтобы поместить эти данные в listView.
Я уже создал представление и попробовал несколько вещей (например, это руководство: https://www.journaldev.com/21839/ios-swift-json-parsing-tutorial), чтобы проанализировать этот JSON, но безуспешно.
Вот код, который я пробовал:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var labelHeader: UILabel!
@IBOutlet weak var tableView: UITableView!
var channelList = [channelData]()
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "channels", withExtension: "json")
guard let jsonData = url
else{
print("data not found")
return
}
guard let data = try? Data(contentsOf: jsonData) else { return }
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else{return}
if let dictionary = json as? [String: Any] {
if let title = dictionary["title"] as? String {
print("in title")
labelHeader.text = title
}
if let data = dictionary["data"] as? Any {
print("data is \(data)")
}
if let date = dictionary["date"] as? Date {
print("date is \(date)")
}
// And so on
for (key, value) in dictionary {
print("Key is: \(key) and value is \(value)" )
//This print the whole JSON to the console.
}
}
//Now lets populate our TableView
let newUrl = Bundle.main.url(forResource: "channels", withExtension: "json")
guard let j = newUrl
else{
print("data not found")
return
}
guard let d = try? Data(contentsOf: j)
else { print("failed")
return
}
guard let rootJSON = try? JSONSerialization.jsonObject(with: d, options: [])
else{ print("failedh")
return
}
if let JSON = rootJSON as? [String: Any] {
labelHeader.text = JSON["id"] as? String //Should update the Label in the ListView with the ID found in the JSON
guard let jsonArray = JSON["type"] as? [[String: Any]] else {
return
}
let name = jsonArray[0]["name"] as? String
print(name ?? "NA")
print(jsonArray.last!["date"] as? Int ?? 1970)
channelList = jsonArray.compactMap{return channelData($0)}
self.tableView.reloadData()
}
}
Вот пример файла JSON:
{
"format": "json",
"data": [
{
"type": "channel",
"id": "123",
"updated_at": "2019-05-03 11:32:57",
"context": "search",
"relationships": {
"recipients": [
{
"type": "user",
"id": 321,
"participant_id": 456
}
],
"search": {
"type": "search",
"title": "Title"
},
}
},
Я бы хотел найти лучший способ работы с этим JSON.
Пока я не могу получить данные в listView. Самое большее, что у меня есть, это мой JSON в консоли xCode (по крайней мере, это означает, что я могу открыть JSON).