skip to Main Content

How to make a struct model with this JSON? I’ve watched many tutorials on youtube but I’m still confused, and what’s the meaning of using enum on struct?

{
  "err_code": 0,
  "data": {
    "message": "Success",
    "result": {
      "check_in": [
        {
          "created_at": "2022-06-20 10:00:37",
          "late": "True",
          "location": "Jl. H. Asmawi No.63, Beji, Kecamatan Beji, Kota Depok, Jawa Barat 16421, Indonesia",
          "place": "GRIT OFFICE",
          "folder": "./pegawai/grit/2022/06/20/masuk/10/00/",
          "filename": "0000_rakha_fatih_athallah_picture.jpg",
          "tujuan": "",
          "link": "http://103.140.90.10:8081/face-recognition/client/python/pegawai/grit/2022/06/20/masuk/10/00/0000_rakha_fatih_athallah_picture.jpg"
        },
        {
          "created_at": "2022-06-16 11:23:12",
          "late": "True",
          "location": "Jl. H. Asmawi No.63, Beji, Kecamatan Beji, Kota Depok, Jawa Barat 16421, Indonesia",
          "place": "GRIT OFFICE",
          "folder": "./pegawai/grit/2022/06/16/masuk/11/23/",
          "filename": "0000_rakha_fatih_athallah_picture.jpg",
          "tujuan": "",
          "link": "http://103.140.90.10:8081/face-recognition/client/python/pegawai/grit/2022/06/16/masuk/11/23/0000_rakha_fatih_athallah_picture.jpg"
        }
      ],
      "check_out": []
    }
  }
}

And this is my struct model. This is important because I want to use jsondecoder with this struct. I want using jsondecoder later.

import Foundation

struct jsonData : Codable{
    var err_code : Int
    var data : Data
    
    enum CodingKeys: String, CodingKey {
            case err_code = "err_code"
            case data = "data"
        }
}

struct Data: Codable{
    var message : String
    var result  : Result
}

struct Result : Codable {
    var check_in  : [Checkin] = []
}

struct Checkin : Codable{
    var created_at : String
    var late : String
    var location : String
    var place : String
    var folder : String
    var tujuan : String
    var link : String
    
    enum CodingKeys: String, CodingKey {
            case created_at = "created_at"
            case late = "late"
            case location = "location"
            case place = "place"
            case folder = "folder"
            case tujuan = "tujuan"
            case link = "link"
        }
}

2

Answers


  1. We use CodingKeys in order to use custom names for the ones in the JSON.

    For example, you have created_at but you don’t want the underscore, what you would do is name your variable createdAt and in the enum add case createdAt = "created_at"

    As for the decoding part, it’s actually pretty easy:

    do {
        //let data = the json data you got.
        let decoder = JSONDecoder()
        let model = try decoder.decode(jsonData.self, from: data)
    }catch {
        print(String(describing: error))
    }
    

    Please note that we don’t use lowercase letters when naming structs, classes, actors & enums.

    Edit: Thanks to Marek R for pointing out that sometimes the names in the JSON can match keywords specific to the used language (i.e: Swift), so it is necessary to implement CodingKeys.

    Login or Signup to reply.
  2. I think the structs you have are very close to what is required, just minor tweaks such as:

    struct Response: Codable{
        var err_code: Int
        var data: DataObj
    }
    
    struct DataObj: Codable{
        var message: String
        var result: Result
    }
    
    struct Result: Codable {
        var check_in: [Checkin]
    }
    
    struct Checkin: Codable, Hashable {
        var created_at: String
        var late: String
        var location: String
        var place: String
        var folder: String
        var tujuan: String
        var link: String
    }
    

    Use it like this:

    struct ContentView: View {
        @State var apiResponse: Response?
        
        var body: some View {
            VStack {
                if let response = apiResponse {
                    Text("message: (response.data.message) ")
                    Text("check_in.count: (response.data.result.check_in.count) ")
                List {
                    ForEach(response.data.result.check_in, id: .self) { chk in
                        Text("created_at: (chk.created_at) ")
                    }
                }
                }
            }
            .onAppear {
                let jsonStr = """
                     {
                     "err_code": 0,
                     "data": {
                     "message": "Success",
                     "result": {
                     "check_in": [
                     {
                     "created_at": "2022-06-20 10:00:37",
                     "late": "True",
                     "location": "Jl. H. Asmawi No.63, Beji, Kecamatan Beji, Kota Depok, Jawa Barat 16421, Indonesia",
                     "place": "GRIT OFFICE",
                     "folder": "./pegawai/grit/2022/06/20/masuk/10/00/",
                     "filename": "0000_rakha_fatih_athallah_picture.jpg",
                     "tujuan": "",
                     "link": "http://103.140.90.10:8081/face-recognition/client/python/pegawai/grit/2022/06/20/masuk/10/00/0000_rakha_fatih_athallah_picture.jpg"
                     },
                     {
                     "created_at": "2022-06-16 11:23:12",
                     "late": "True",
                     "location": "Jl. H. Asmawi No.63, Beji, Kecamatan Beji, Kota Depok, Jawa Barat 16421, Indonesia",
                     "place": "GRIT OFFICE",
                     "folder": "./pegawai/grit/2022/06/16/masuk/11/23/",
                     "filename": "0000_rakha_fatih_athallah_picture.jpg",
                     "tujuan": "",
                     "link": "http://103.140.90.10:8081/face-recognition/client/python/pegawai/grit/2022/06/16/masuk/11/23/0000_rakha_fatih_athallah_picture.jpg"
                     }
                     ],
                     "check_out": []
                     }
                     }
                     }
                     """
                // simulated response data
                let data = jsonStr.data(using: .utf8)!
                do {
                    self.apiResponse = try JSONDecoder().decode(Response.self, from: data)
                    print("n---> apiResponse (apiResponse)")
                }
                catch {
                    print(" error (error)")
                }
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search