-2

In iOS, how can I parse this JSON?

{
  "status": 1,
  "data": [
    {
      "month": "8-2019",
      "jobs": [
        {
          "jobId": 4,
          "jobTitle": "",
          "jobDesc": "",
          "jobDate": "26 Sep 2019",
          "jobVenue": "Singapore",
          "jobAccept": "N"
        }
      ]
    }
  ],
  "message": "Success"
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Aries Code
  • 19
  • 2

1 Answers1

4

You can use a service like quicktype to create Codable classes. As a starting point you should read more about the Codable Protocol

You can use the following code to parse this JSON:

import Foundation

// MARK: - Root
struct Root: Codable {
    let status: Int
    let data: [Datum]
    let message: String
}

// MARK: - Datum
struct Datum: Codable {
    let month: String
    let jobs: [Job]
}

// MARK: - Job
struct Job: Codable {
    let jobID: Int
    let jobTitle, jobDesc, jobDate, jobVenue: String
    let jobAccept: String

    enum CodingKeys: String, CodingKey {
        case jobID = "jobId"
        case jobTitle, jobDesc, jobDate, jobVenue, jobAccept
    }
}

You can use this code to convert the JSON to an object:

let root= try? JSONDecoder().decode(Root.self, from: jsonData)
inexcitus
  • 2,471
  • 2
  • 26
  • 41
  • 2
    Where did you copy this code from? I am seriously curious about this since it is not the first time on SO I see someone use the weird class `newJSONDecoder` in an answer. – Joakim Danielson Nov 07 '19 at 07:24
  • 1
    I already posted the answer to your question: the structs are auto-generated by the `quicktype` web site. You simply post your JSON and it will generate all the necessary classes/structs for decoding it. Pretty useful. – inexcitus Nov 07 '19 at 07:26
  • Sorry, you are right. This seems like an error in the generated code. It should be `JSONDecoder`. – inexcitus Nov 07 '19 at 07:33
  • Ok now I see. I usually only generate the structs and not the rest of the code but now I tested that and I see that newJSONDecoder is actually a function generated by quicktype that returns a decoder. This also means that it is quicktype that generates the horrible `try?` for error handling – Joakim Danielson Nov 07 '19 at 07:49