UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.