Parsing JSON into Swift Objects directly

      No Comments on Parsing JSON into Swift Objects directly

Parsing JSON data in into swift objects have become super easy with Swift 4 JSONDecoder.Given below is a simple example which hits a Api and parses the JSON data directly to student object.We are assuming that we have a JSON response which has same keys as names of properties.

import UIKit
struct Student:Decodable{// property name should be same as json key name
    let name:String?
    let roll:Int?
}
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = "http//:www.yoururlnotmine.com/test/blah/blah"
        guard let url  =  URL.init(string: urlString) else { return }
        URLSession.shared.dataTask(with: url) { (data, responce, error) in
            guard let data = data else{return}
            do{
            let student = try JSONDecoder().decode(Student.self, from: data)
                //mapped name to student.name
                //mapped roll to student.roll
                print(student.name ?? "no name")
            }
            catch{
                //error handling
            }
            
        }
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

In order to pull it off successfully ,there are few points to be noted

  1. Class should conform to Decodable protocol
  2. Class properties should have same name as JSON keys so that they can be mapped.
  3. Class should have the same structure as JSON
  4. Properties which can be absent in JSON should be marked optional using “?” else it will cause run time error.

Parsing Complex JSON Structures

continued on next page

A pat on the back !!