简体   繁体   中英

how convert JSON response to Array in swift?

func llamadaApiDos(postData: (Data),empresa: String,boundary: String) -> [String] {
        
        var request = URLRequest(url: URL(string: "https://www.something.com")!,timeoutInterval: Double.infinity)
        request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        
        request.httpMethod = "POST"
        request.httpBody = postData
        
        var success = false
        var serviceResponse = [""]
        let semaphore = DispatchSemaphore(value: 0)
        let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
            if let error = error {
                print("Error while trying to re-authenticate the user: \(error)")
            } else if let response = response as? HTTPURLResponse,
                      300..<600 ~= response.statusCode {
                print("Error while trying to re-authenticate the user, statusCode: \(response.statusCode)")
            } else if let data = data {
                let loginDataModel = try! JSONDecoder().decode(responseLogin.self,from: data)
                serviceResponse = JSONDecoder.decode(loginDataModel)
                success = true
            }else{
                success = true
            }
            semaphore.signal()
        })
        
        task.resume()
        _ = semaphore.wait(timeout: DispatchTime.distantFuture)
        
        if success
        {
            return serviceResponse
        }else
        {
            return ["Error"]
        }
    }

Cannot assign value of type '(T.Type, Data) throws -> T' to type '[String]'

I need to convert the JSON response into an array that can be validated in another function, but I don't know what type of data I should return, I'm sorry if it's not well understood, my English isn't very good either.

To convert the JSON response to an array in Swift, you can use the JSONSerialization class to convert the response data to a dictionary, then access the array stored in the dictionary using the key for the array.

Here's an example:

let json = try JSONSerialization.jsonObject(with: data, options: [])

if let array = json["keyForArray"] as? [String] {
    // Use the array here
}

In your code, you can use this approach to convert the JSON response to an array, then return the array from the llamadaApiDos function.

Here's how your function would look like with this change:

func llamadaApiDos(postData: (Data),empresa: String,boundary: String) -> [String] {
        
    var request = URLRequest(url: URL(string: "https://www.something.com")!,timeoutInterval: Double.infinity)
    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    
    request.httpMethod = "POST"
    request.httpBody = postData
    
    var success = false
    var serviceResponse = [""]
    let semaphore = DispatchSemaphore(value: 0)
    let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
        if let error = error {
            print("Error while trying to re-authenticate the user: \(error)")
        } else if let response = response as? HTTPURLResponse,
                  300..<600 ~= response.statusCode {
            print("Error while trying to re-authenticate the user, statusCode: \(response.statusCode)")
        } else if let data = data {
            // Convert the JSON response to an array
            let json = try JSONSerialization.jsonObject(with: data, options: [])

            if let array = json["keyForArray"] as? [String] {
                // Use the array here
                serviceResponse = array
                success = true
            }
        }else{
            success = true
        }
        semaphore.signal()
    })
    
    task.resume()
    _ = semaphore.wait(timeout: DispatchTime.distantFuture)
    
    if success
    {
        return serviceResponse
    }else
    {
        return ["Error"]
    }
}

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