[英]How to parse JSON correctly? Swift
不明白如何解析 .json 文件?
我有一個 model:
struct Subject: Decodable {
struct Schedule: Decodable {
let parity: String
let type: String
let other: String
let title: String
let author: String
let location: String
let aHref: String
}
let schedule: [Schedule]
}
有一個 schedule.swift 文件:
class JsonSchedule {
let jsonSchedule = """
{
"pageURL":"https://www.sgu.ru/schedule/mm/do/231",
"schedule":[
[
[
{
"parity":"чис.",
"type":"лек.",
"other":"",
"title":"Общая физика",
"author":"Сотов Л. С.",
"location":"3 корп. ауд.34",
"aHref":"https://www.sgu.ru//person/sotov-leonid-sergeevich"
}
],
...
...
...
}
""".data(using: .utf8)!
有一個視圖 Controller:
class TableViewController: UITableViewController {
let subject = JSONDecoder.decode(Subject.self, from: JsonSchedule.jsonSchedule)
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
return cell
}
}
我究竟做錯了什么?
錯誤:let subject = JSONDecoder.decode(Subject.self, from: JsonSchedule.jsonSchedule) 實例成員 'jsonSchedule' 不能用於類型 'JsonSchedule'; 你的意思是使用這種類型的值嗎? 實例成員 'decode' 不能用於類型 'JSONDecoder'; 你的意思是使用這種類型的值嗎?
您可以使用這一行,但不是最好的代碼
let subject = try? JSONDecoder().decode(Subject.self, from: JsonSchedule.jsonSchedule)
並像這樣更改 JsonShedule
static let jsonSchedule
為了獲得最佳實踐,將此行放入viewDidLoad並添加do - catch塊
var subject: Subject?{
didSet{
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
do{
subject = try JSONDecoder().decode(Subject.self, from: JsonSchedule.jsonSchedule)
}catch(let err){
print(err.localizedDescription)
}
}
Aa 和您的 json 在數據中存在一些錯誤。 使用這個正確的完整示例
{
"pageURL":"https://www.sgu.ru/schedule/mm/do/231",
"schedule":[
{
"parity":"чис.",
"type":"лек.",
"other":"",
"title":"Общая физика",
"author":"Сотов Л. С.",
"location":"3 корп. ауд.34",
"aHref":"https://www.sgu.ru//person/sotov-leonid-sergeevich"
}
]
}
""".data(using: .utf8)!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.