簡體   English   中英

如何將 JSON 響應轉換為 swift 中的數組?

[英]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"]
        }
    }

無法將類型“(T.Type, Data) throws -> T”的值分配給類型“[String]”

我需要將 JSON 響應轉換成一個數組,可以在另一個 function 中驗證,但我不知道我應該返回什么類型的數據,如果不好理解,我很抱歉,我的英語也不是很好.

要將 JSON 響應轉換為 Swift 中的數組,您可以使用 JSONSerialization class 將響應數據轉換為字典,然后使用數組的鍵訪問存儲在字典中的數組。

這是一個例子:

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

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

在您的代碼中,您可以使用此方法將 JSON 響應轉換為數組,然后從 llamadaApiDos function 返回該數組。

以下是您的 function 進行此更改后的樣子:

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"]
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM