I try to convert a JSON to an Array but I face some issue and do not know how to sort it out. I use Swift 5 and Xcode 12.2.
Here is the JSON from my PHP query:
[ { Crewcode = AAA; Phone = 5553216789; Firstname = Philip; Lastname = MILLER; email = "[email protected]"; }, { Crewcode = BBB; Phone = 5557861243; Firstname = Andrew; Lastname = DEAN; email = "[email protected]"; } ] And here is my Swift code :
let url: URL = URL(string: "https://xxx.php")! let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default) let task = defaultSession.dataTask(with: url) { (data, response, error) in if error != nil { print("Failed to download data") } else { print("Data downloaded") do { if let jsondata = (try? JSONSerialization.jsonObject(with: data!, options: [])) { print(jsondata) struct Crew: Decodable { var Code: String var Phone: String var Firstname: String var Lastname: String var email: String } let decoder = JSONDecoder() do { let people = try decoder.decode([Crew].self, from: jsondata as! Data) print(people) } catch { print(error) } } } } } task.resume() When I run my code I get the following error:
Could not cast value of type '__NSArrayI' (0x7fff86b930b0) to 'NSData' (0x7fff86b911e8). 2020-12-09 14:52:48.988468+0100 FTL[57659:3019805] Could not cast value of type '__NSArrayI' (0x7fff86b930b0) to 'NSData' (0x7fff86b911e8). Could not cast value of type '__NSArrayI' (0x7fff86b930b0) to 'NSData' (0x7fff86b911e8).
Should you have any idea to get it right, I thank you in advance for your assistance on this !
Codeparameter that your JSON doesn't include. If it's optional, then you need to make it optional (String?).