0

I have a JSON of following format in which there is a student object. student object has multiple students listed in it

Student {
    student1: {
        id: "12",
        name: "jack",
    },
    student2: {
        id: "2323",
        name: "lewis"
    },
    student3: {
        id: "1212",
        name: "pint"
    }
}

I would like to convert this into an array of student objects as shown below. How do i do this using decodable?

struct student: Decodable {
    let name: String
    let id: String
}

2 Answers 2

2

Perhaps this is what you want:

let json = """
{
  "student": {
      "student1": {
          "id": "12",
          "name": "jack",
      },
      "student2": {
          "id": "2323",
          "name": "lewis"
      },
      "student3": {
          "id": "1212",
          "name": "pint"
      }
  }
}
"""

struct Student: Decodable {
  let id: String
  let name: String
}

struct StudentContainer: Decodable {
  let students: [Student]

  private enum CodingKeys: String, CodingKey {
      case student
  }

  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    let studentsDict = try container.decode([String: Student].self, forKey: .student)
    self.students = studentsDict.map { $0.value }
  }
}

let result = try? JSONDecoder().decode(StudentContainer.self, from: json.data(using: .utf8)!)
Sign up to request clarification or add additional context in comments.

Comments

0

Apologies, I've misread this a bit so I'll have a go again.

To make an array you could do something like the following:

struct Students: Codable {
    let students: [Student]
}

struct Student: Codable {
    let name: String
    let id: String
} 

This is enough to code the students into an array. Simply pass the JSON data with Students.

You will have to edit your JSON slightly, like this:

{
    "students": [
        {
            id: "12",
            name: "jack",
        },
        {
            id: "2323",
            name: "lewis"
        },
        {
            id: "1212",
            name: "pint"
        }
    ]
}

1 Comment

The JSON is not something in my control

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.