Search code examples
iosswiftxcodejsondecoder

Unable to get data from JSONDecoder ,that's right, I made up the structure?


I have such a structure, I took a piece to get the data. Here's my code.Why can't I get data from the Api?Can anyone help and example write in the answer.It seems like all are correct. I will be very grateful.

[{
    "id": 142636,
    "apiId": 353056,
    "shortName": "K. McKenzie-Lyle",
    "firstName": "Kai",
    "middleName": null,
    "lastName": "McKenzie-Lyle",
    "imageFileName": null,
    "height": 195,
    "weight": 86,
    "birthDate": "1997-11-30T00:00:00",
    "contractExpiration": null,
    "onLoanSquadTillDate": null,
    "oldApiId": 344534,
    "age": 22,
    "birthAreaId": 80,
    "passportAreaId": 110,
    "footName": "Right",
    "male": true,
    "currentSquadId": 20401,
    "parentSquadId": 46,
    "nationalSquadId": 31885,

    }]

My code struct tried decode and "id" , etc.

struct PlayerRoster:Codable {
    let id: String?
    let apiId:String?
    let shortName: String?
    let firstName: String?
    let middleName:String?
    let lastName:String?
    let imageFileName:String?
    let height:Double?
    let weight:Double?


}

My load url api adress.

func loadingApi(){
            let urlData = "https://apidev.transferroom.com/api/values"

            guard let url = URL(string: urlData) else { return }

            let task = URLSession.shared.dataTask(with: url) { (data,response,error) in


                guard let data = data else { return }
                guard error == nil else {return}


                    do {
                        let decoder = JSONDecoder()

                        //using the array to put values
                      let player = try decoder.decode(PlayerRoster.self, from: data)
                      self.updatedPlauers = player




                    } catch let error as NSError {
                        print("Failed to load: \(error.localizedDescription)")
                    }
                }


            task.resume()

        }
    }

Solution

  • You need

    let player = try decoder.decode([PlayerRoster].self, from: data)
    

    the root of your json is an array indicated by [] , doing this would help knowing the problem

    } catch {
       print("Failed to decode : \(error)")
     }
    

    plus

    let id: Int?
    let apiId:Int?