[英]How to parse JSON correctly? Swift
Don't understand how to parse the.json file?不明白如何解析 .json 文件?
I have a model:我有一个 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]
}
there is a schedule.swift file:有一个 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)!
there is a View Controller:有一个视图 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
}
}
What am I doing wrong?我究竟做错了什么?
Error: let subject = JSONDecoder.decode(Subject.self, from: JsonSchedule.jsonSchedule) Instance member 'jsonSchedule' cannot be used on type 'JsonSchedule';错误:let subject = JSONDecoder.decode(Subject.self, from: JsonSchedule.jsonSchedule) 实例成员 'jsonSchedule' 不能用于类型 'JsonSchedule'; did you mean to use a value of this type instead?
你的意思是使用这种类型的值吗? Instance member 'decode' cannot be used on type 'JSONDecoder';
实例成员 'decode' 不能用于类型 'JSONDecoder'; did you mean to use a value of this type instead?
你的意思是使用这种类型的值吗?
You can use this line, but is not best code您可以使用这一行,但不是最好的代码
let subject = try? JSONDecoder().decode(Subject.self, from: JsonSchedule.jsonSchedule)
And change JsonShedule like this并像这样更改 JsonShedule
static let jsonSchedule
For best practics put this line into viewDidLoad and add do - catch block为了获得最佳实践,将此行放入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)
}
}
Aaand your json have some errors in shedule data. Aa 和您的 json 在数据中存在一些错误。 Use this correct full example
使用这个正确的完整示例
{
"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.