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
We use
CodingKeys
in order to use custom names for the ones in theJSON
.For example, you have
created_at
but you don’t want the underscore, what you would do is name your variablecreatedAt
and in theenum
addcase createdAt = "created_at"
As for the decoding part, it’s actually pretty easy:
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 implementCodingKeys
.I think the structs you have are very close to what is required, just minor tweaks such as:
Use it like this: