1

I am making an HTTP GET request and I want to save the JSON response that looks like this:

{
    "code": 200,
    "status": "success",
    "patients": [
        {
            "_id": "5e77c7bbc7cbd30024f3eadb",
            "name": "Bogdan Patient",
            "username": "bogdanp",
            "phone": "0732958473"
        },
        {
            "_id": "5e77c982a2736a0024e895fa",
            "name": "Robert Patient",
            "username": "robertp",
            "phone": "0739284756"
        }
    ]
}

And here is my struct:

struct Doctor: Codable, Identifiable {
  let id = UUID()
  let patients: [Patients]
}

struct Patients: Codable {
  let id: String
  let name: String
  let phone: String
}
3
  • You have to add CodingKeys in both structs to skip id in Doctor and to map _id in Patients. Commented Mar 27, 2020 at 9:02
  • And how do I do that? Can you post it in an answer? I am not familiar with CodingKeys. Commented Mar 27, 2020 at 9:04
  • Then you should do some research, maybe read this article from Apple Commented Mar 27, 2020 at 9:07

1 Answer 1

1

As per your model, id is expected in the JSON whereas the keyname in the JSON is _id.
You can use CodingKeys to fix this:

struct Patients: Codable {
    let id: String
    let name: String
    let phone: String

    enum CodingKeys: String, CodingKey {
        case id = "_id"
        case name
        case phone
    }
}

CodingKeys creates a map between the keynames in your model and the keynames in the JSON response.
There are other reasons to use CodingKeys but for your current purpose this is enough.

Read More: Codable in Swift

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.