Parsing JSON into Swift Objects directly

      No Comments on Parsing JSON into Swift Objects directly

In the previous example we dealt with a very simple JSON and decoded a JSON response into an object.Now we will step it up a bit and will parse a JSON response to array of object. See the code example below

import UIKit
struct Student:Decodable{
    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 students = try JSONDecoder().decode([Student].self, from: data)
                print(students.first?.name ?? "no name")
                
                // now students is an array of [Student]
            }
            catch{
                //error handling
            }
            
        }
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

As you can see the magic line which did the change was

let students = try JSONDecoder().decode([Student].self, from: data)

                print(students.first?.name ?? “no name”)

So it was pretty straight forward now lets try some thing different. Lets have a Teacher struct with subject and array of student as properties and parse JSON directly into it.

First we will construct a Teacher struct with array of student as one of its properties and make in conform to decodable

struct Teacher:Decodable {
    let subject:String?
    let students:[Student]?
}

After that we will make changes in JSONDecoder().decode method

do{
           let teacher = try JSONDecoder().decode(Teacher.self, from: data)
               print(teacher.subject ?? "no name")
               print(teacher.students?.first?.name ?? "no name")
               // now students is an array of [Student]
  }
  catch{
        //error handling
  }

After making these changes , final code will look like this

import UIKit
struct Teacher:Decodable {
    let subject:String?
    let students:[Student]?
}
struct Student:Decodable{
    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 teacher = try JSONDecoder().decode(Teacher.self, from: data)
                print(teacher.subject ?? "no name")
                print(teacher.students?.first?.name ?? "no name")
                // now students is an array of [Student]
            }
            catch{
                //error handling
            }
            
        }
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

So as you have seen above how easy it is to parse a JSON directly into Swift Object using Swift 4. Comment if you have any suggestions or requests.

 

A pat on the back !!