简体   繁体   中英

How to parse JSON correctly? Swift

Don't understand how to parse the.json file?

I have a 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:

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:

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'; did you mean to use a value of this type instead? Instance member 'decode' cannot be used on type '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

   static let jsonSchedule 

For best practics put this line into viewDidLoad and add do - catch block

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. 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)!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM