Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Parsing JSON Using Codable Parsing Different JSON Structures Nested Objects

Please help! Problem decoding nested array of Json

Any feedback is greatly appreciated as its not decoding

let json = """ { "success":true, "data": [ { "sport_key":"americanfootball_nfl", "sport_nice":"NFL", "teams":[ "Kansas City Chiefs", "Oakland Raiders" ] }, {

"sport_key":"americanfootball_nfl", "sport_nice":"NFL", "teams":[ "Seahawks", "patriots" ] }]} """.data(using: .utf8)

struct Outer: Codable { let success: Bool let data: [Json]

enum CodingKeys: CodingKey {
    case success
    case data
}

init(from decoder: Decoder) throws {
    let valueContainer = try decoder.container(keyedBy: CodingKeys.self)
    success = try valueContainer.decode(Bool.self, forKey: .success)
    data = try valueContainer.decode([Json].self, forKey: .data)
}

}

struct Json: Codable { var teams: [String]

enum InnerCodingKeys:  CodingKey {
    case teams

}

init (from decoder: Decoder) throws {

    let innerContainer = try decoder.container(keyedBy: InnerCodingKeys.self)
    teams = try innerContainer.decode([String].self, forKey: .teams)
}

}

let jsonDecoder = JSONDecoder() let body = String(data: json!, encoding: .utf8) let decodedData = try jsonDecoder.decode([Outer].self, from: json!)