hgiraud
hgiraud

Reputation: 25

Problem converting JSON to Array with Swift

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 !

Upvotes: 0

Views: 59

Answers (1)

vadian
vadian

Reputation: 285069

You are deserializing the JSON twice by mixing up JSONSerialization and JSONDecoder.

Delete the first one

 if let jsondata = (try? JSONSerialization.jsonObject(with: data!, options: [])) {

– By the way the JSON in the question is neither fish nor fowl, neither JSON nor an NS.. collection type dump –

and replace

let people = try decoder.decode([Crew].self, from: jsondata as! Data)

with

let people = try decoder.decode([Crew].self, from: data!)

and the struct member names must match the keys otherwise you have to add CodingKeys

Upvotes: 1

Related Questions