简体   繁体   中英

SWIFT : I cannot parse data from URL?

I am trying to parse data from an url, however I am unable to add the objects into my games array, I fall into the debugprint("failed to parse data"). My class Game Inherits from Codable, so I don't really see what I am missing.

var games = [Game]()

    func download(at url: String, handler: @escaping (Data?) -> Void)
    {
        // 1 - Create URL
        guard let url = URL(string: url) else {
            debugPrint("Failed to create URL")
            handler(nil)
            return
        }
        // 2 - Create GET Request
        var request: URLRequest = URLRequest(url: url)
        request.httpMethod = "GET"
        // 3 - Create download task, handler will be called when request ended
        let task = URLSession.shared.dataTask(with: request) {
            (data, response, error) in handler(data)
        }
        task.resume()
    }
    func getGames() {
        // 1 - Download games
        download(at: "https://education.3ie.fr/ios/StarterKit/GameCritic/GameCritics.json")
        { (gameData) in
            if let gameData = gameData {
                // 2 - Decode JSON into a array of Game object
                let decoder: JSONDecoder = JSONDecoder()
                do {
                    self.games = try decoder.decode([Game].self, from: gameData)
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                }
                catch {
                    debugPrint("Failed to parse data") // I fail here
                }
            }
            else
            {
                debugPrint("Failed to parse data - error: \(error)")
            }
        }
    }

    override func viewDidLoad() {

        getGames()
        for elm in games
        {
            debugPrint(elm)
        }
        super.viewDidLoad()
    }

output:

"Failed to parse data - error: keyNotFound(CodingKeys(stringValue: \"small_path\", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: \"Index 0\", intValue: 0)], debugDescription: \"No value associated with key CodingKeys(stringValue: \\\"small_path\\\", intValue: nil) (\\\"small_path\\\").\", underlyingError: nil))"

It appears you are almost there:)

You say

I replaced small_path with smallImageUrl

But have a look at the JSON from: https://education.3ie.fr/ios/StarterKit/GameCritic/GameCritics.json

Here is one item:

{
  "id" : 0,
  "name" : "Shenmue",
  "smallImageURL" : "https://education.3ie.fr/ios/StarterKit/GameCritic/small0.jpg",
  "bigImageURL": "https://education.3ie.fr/ios/StarterKit/GameCritic/big0.jpg",
  "score": 16,
  "platform": "dreamcast"
},

The correct name is smallImageURL but in your Swift Game struct/class you have a property called smallImageUrl (lowercase "rl" in Url compared to uppercase "RL" in the JSON). That is enough for the JSONDecoder to abandon all hope and give up...yes really: :)

So, for a start, try renaming your property from

smallImageUrl

to

smallImageURL

and see where that takes you.

Choosing Different Names for Properties

If you would like to use a different name for your Swift variable than what it is referred to in the JSON you receive, for instance smallImageUrl instead of smallImageURL . I encourage you to have a look at the documentation for Encoding/Decoding, more specific the section called: "Choose Properties to Encode and Decode Using Coding Keys"

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM