TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.