I am trying to parse a JSON object from an API, I have defined the structure of JSON in a separate file.
The parser successfully parses the JSON file, however when calling the getStandings()
function in viewDidLoad()
it returns an empty array.
Can anyone tell me where's my error?
This is the structure of the JSON
EDIT: I went through the similar question however none of the solutions are working on my code, can someone please explain what needs to be added to my code, I am new to this
struct FootballData : Codable{
let response: [Response]
}
struct Response: Codable {
let league: League
}
struct League: Codable {
let id: Int
let name: String
let country: String
let standings : [[Standings]]
}
struct Standings: Codable {
let rank: Int
let team: Team
let points: Int
let goalsDiff: Int
let all: All
}
struct Team: Codable {
let id: Int
let name: String
let logo: String
}
struct All: Codable {
let played: Int
let win: Int
let draw: Int
let lose: Int
}
Here's the code I am using to request data from the API and parse the JSON file.
func getStandings() -> [[Standings]]{
let standings = [[Standings]]()
var request = URLRequest(url: URL(string: "https://v3.football.api-sports.io/standings?league=39&season=2022")!,timeoutInterval: Double.infinity)
request.addValue("639248abcf96cbcebd90cd66aec49db4", forHTTPHeaderField: "x-rapidapi-key")
request.addValue("v3.football.api-sports.io", forHTTPHeaderField: "x-rapidapi-host")
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error == nil && data != nil {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(FootballData.self, from: data!)
let standings = decodedData.response[0].league.standings
print(standings)
} catch {
print(error)
}
}
}
//4. Start the task
task.resume()
return standings
}