BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SOLVED: nested JSON

Forums > SwiftUI

Totally made up data to show the issue I am having. Suppose I have some JSON returned by an API call that looks like this

{
 "students": [
    {
     "id": "asdfgh",
     "name": "Gary",
     "DOB": 2000
    },
    {
     "id": "jklzx",
     "name": "Peter",
     "DOB": 2001
    },
    {
     "id": "qazwsx",
     "name": "Susan",
     "DOB": 2002
    }
    ]
}

and now I want to display all the students names, in a navigation view, this links to another view that shows the name and DOB. Now if the open brace and the "students" tag and closing brace were removed, I would have no trouble decoding the data; but as they are present its causing me problems.

Any ideas on how to do this?

2      

hi Gary,

the list of students is of type [Student] inside a struct with a field named students. this will work, where the term json is the sample String returned from your API.

struct Student: Codable {
    var id: String
    var name: String
    var DOB: Int
}

struct Classroom: Codable {
    var students: [Student]
}

let classroom = try! JSONDecoder().decode(Classroom.self, from: Data(json.utf8))
for student in classroom.students {
    print(student.id)
    print(student.name)
    print(student.DOB)
    print()
}

hope that helps,

DMG

3      

Thanks Jerry, that helps a lot.

2      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.