Q:

How to parse JSON using Codable in Swift?

I am able to parse JSON using JSONSerialization, but unable to parse with Codable.
the json look like this:
[
{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
  }

Please help me with the code.
able to parse using JSONSerialization: data coming
Unable to parse JSON with Codable: data not coming
struct jsonDataModel: Codable{

var name: String
var userName: String
var email: String

init(name: String, username: String, email: String){
    self.name = name
    self.userName = username
    self.email = email
}
}
class WebviewViewController: UIViewController, WKNavigationDelegate {

@IBOutlet weak var testWebView: WKWebView!

//var itemsArray = [jsonDataModel]()

override func viewDidLoad() {
    super.viewDidLoad()
    serviceCall()
    }

   func serviceCall()
    {

        let jsonString = "https://jsonplaceholder.typicode.com/users"

        let jsonData = jsonString.data(using: .utf8)!

            do {
               let jsonDecoder = JSONDecoder()
               let user = try jsonDecoder.decode(jsonDataModel.self, from: jsonData)
                print("all data \(user)")
                print("Hello \(user.name), \(user.userName), \(user.email) ")
            } catch {
                print("Unexpected error: \(error).")
            }
    }
    }

Please help me to parse json with codable.

A:

Try this example.
import UIKit
import Foundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://jsonplaceholder.typicode.com/users")!
        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            do{
                let jsonDataModels = try JSONDecoder().decode([JSONDataModel].self, from: data)
                print(String(data: data, encoding: .utf8)!)
                print("jsonDataModels: \(jsonDataModels)")
            }catch{}
        }
        task.resume()

    }
}

struct JSONDataModel: Codable {
    let id: Int
    let name, username, email: String
    let address: Address
    let phone, website: String
    let company: Company
}

struct Address: Codable {
    let street, suite, city, zipcode: String
    let geo: Geo
}

struct Geo: Codable {
    let lat, lng: String
}

struct Company: Codable {
    let name, catchPhrase, bs: String
}

