WepsTech
The world of development
In this tutorial, We are going to cover json parsing in iOS. And we will see a very sort method for parsing the JSON into the class model format. Now a days all the application is using web services for receiving and sending data from one client to another client. That’s why, It’s become necessity to learn a sort method for Json parsing in iOS with swift 5. So let’s start and learn..
So Let’s begin, Before parsing the JSON response you people must know the type of JSON Response. It may be array, string, integer, object or dictionary. Initially, it was hard for me to understand JSON parsing. But I realized over time that it’s actually very easy to use. You only need to understand the Response type. Im this tutorial we are taking the reference of the following json file.
{ "posts": [ { "id": 1, "title": "Post 1" }, { "id": 2, "title": "Post 2" }, { "id": 3, "title": "Post 3" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 }, { "id": 2, "body": "some comment", "postId": 1 } ], "profile": { "name": "typicode" } }
So this JSON we will parse. And this JSON you can get over here for example – https://my-json-server.typicode.com/typicode/demo/db
After all this information we will do coding for this. Very first we will write a model class. And for reference you can also watch the video for deep understanding.
import Foundation class DB: Codable { var posts : [Post] var comments : [Comments] var profile : Profile! class Post: Codable { var id : Int! var title : String! } class Comments: Codable { var id : Int! var body :String! var postId : Int! } class Profile: Codable { var name : String! } }
So, this was an model class. Now we will code for parsing our JSON into this Model format.
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. jsonPars() } func jsonPars() { guard let url = URL(string: "https://my-json-server.typicode.com/typicode/demo/db") else { return } let task = URLSession.shared.dataTask(with: url) { (data, response, error) in guard let responseData = data, error == nil else { print(error.debugDescription) return } let codable = JSONDecoder() do { let db = try codable.decode(DB.self, from: responseData) for post in db.posts{ print("Post ID : \(post.id!)") print("Post Title : \(post.title!)") } print(db.profile.name ?? "NOT EXIST") }catch let error { print(error.localizedDescription) } } task.resume() } }
Wonderful, You have achieved your goal for json parsing in iOS. In Addition, We have more tutorials. If you want to become a smart developer then you should go with the following tutorials.