【发布时间】:2019-05-07 19:22:11
【问题描述】:
我有一个 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。我拥有的最多的是我在 xCode 控制台中的 JSON(至少这意味着我能够打开 JSON)。
【问题讨论】:
-
在准备好回答这个问题之前,您还有很长的路要走。请参阅JSONSerialization 课程以了解开始的地方。还有一些用于处理 JSON 数据的库。
-
解析 JSON 是最常见的问题之一。有more than 4000 related questions
-
我不想发布我的整个代码,但我会用更多代码更新问题。 @vadian 问题是我发现可能与我的案例有关的问题已经过时(3 年或更长时间)。
-
你没有意识到你的 JSON 不包含像
name和date这样的键吗?请学习阅读 JSON,这真的很容易。我写了一个快速概述here -
@vadian 不,我没有。我是一个使用 JSON 的菜鸟,并且一年多没有使用 Swift,所以我生疏了。我会看看你的答案,谢谢。
标签: json swift uitableview parsing