如何在Swift IOS请求中获取数组响应



我以这样的方式发送请求:

let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                // check for fundamental networking error
                print("error=(String(describing: error))")
                completion(nil)
                return
            }

            print("********_Respone status code is: ",(response as! HTTPURLResponse).statusCode)
            print("********_Respone url code is: ",response?.url as Any )
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
                let res:HTTPURLResponse = response as! HTTPURLResponse
                print(json)// yessssssssss goooood
            } catch {
                completion(nil)
                return
            }
}

        task.resume()

当响应是字典时,它正常工作,但是当我的响应是一个数组时,显示此错误:

请帮助我解决此问题。

一旦 qson questerialize ,并省略了选项, ArrayDictionary不是 n em> fragmented 。然后可选绑定结果。

do {
     let json = try JSONSerialization.jsonObject(with: data)
     if let jsonArray = json as? [[String:Any]] {
        print("json is array", jsonArray)
     } else if let jsonDictionary = json as? [String:Any] {
        print("json is dictionary", jsonDictionary)
     } else {
        print("This should never be displayed")
     }
} ...

如果结果应该仅是数组或字典,则可以将结果强制为字典并删除最后一个else子句

do {
     let json = try JSONSerialization.jsonObject(with: data)
     if let jsonArray = json as? [[String:Any]] {
        print("json is array", jsonArray)
     } else {
        let jsonDictionary = json as! [String:Any] 
     }
} ...

最新更新