Json解析错误:在Swift iOS中使用未声明的类型'Foundation'

时间:2018-10-06 16:13:54

标签: ios json swift parsing jsonparser

我正在使用Swift创建一个应用,其中必须使用以下URL显示国家列表:

  

https://restcountries.eu/rest/v2/all

在这里,我只需要获取name密钥并添加到我的NSMutableArray中。当我尝试使用URLSession解析它时,出现错误:

expression produced error: error: /var/folders/_3/27lhgzw9699c4_yg37r72_d80000gp/T/expr40-bcf47d..swift:1:65: error: use of undeclared type 'Foundation'
Swift._DebuggerSupport.stringForPrintObject(Swift.UnsafePointer<Foundation.Data>(bitPattern: 0x105c0c2f0)!.pointee)

下面是我的代码:

func fetchCountryList(countryURL:URL, completion:@escaping (NSDictionary) -> ()) {

            print(countryURL)

            let request = NSMutableURLRequest( url: countryURL as URL)

            let task = URLSession.shared.dataTask(with: request as URLRequest) {
                data, response, error in
                do{
                    if let data = data,
                        let jsonString =  try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                        , error == nil {
                        completion(jsonString)
                    } else {
                        print("error=\(error!.localizedDescription)")
                        let errorDict = ["error_status":true,"message":error!.localizedDescription] as [String : Any]
                        completion(errorDict as NSDictionary)

                    }
                }
                catch{
                    print("error=\(error.localizedDescription)")
                    let errorDict = ["error_status":true,"message":error.localizedDescription] as [String : Any]
                    completion(errorDict as NSDictionary)

                }

            }
            task.resume()
    }

有人可以在这里建议我我的错误吗?预先感谢!

2 个答案:

答案 0 :(得分:1)

替换

try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

使用

try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String: Any]]

由于它是对象数组,因此我们还需要将json转换为array

要获取array of country names,我们可以通过以下方式实现:

guard let countries = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String: Any]] else {
    return
}
let countryNames = countries.map { $0["name"] as! String }

答案 1 :(得分:0)

替换

 let jsonString =  try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

使用

if let result =  try JSONSerialization.jsonObject(with: data, options:[]) as? [[String:Any]] {
   for item in result {
     print(item["name"])
   }  
 }

响应是数组而不是字典,也不要使用NS东西

  

NSDictionary => [String:Any]

     

NSUrl =>网址

     

NSMutableURLRequest => URLRequest


func fetchCountryList(countryURL:URL, completion:@escaping (_ arr :[[String:Any]]?, _ error:Error?) -> ()) {

            print(countryURL)

            let request = URLRequest( url: countryURL)

            let task = URLSession.shared.dataTask(with: request) {
                data, response, error in
                do{
                    if let data = data,
                        let jsonString =  try JSONSerialization.jsonObject(with: data, options:[]) as? [[String:Any]]
                        , error == nil {
                        completion(jsonString,nil)
                    } else {
                        print("error=\(error!.localizedDescription)")
                        let errorDict = ["error_status":true,"message":error!.localizedDescription] as [String : Any]
                        completion(nil,error)

                    }
                }
                catch{
                    print("error=\(error.localizedDescription)")
                    let errorDict = ["error_status":true,"message":error.localizedDescription] as [String : Any]
                    completion(nil,error)

                }

            }
            task.resume()
    }

致电

serviceModel.fetchCountryList(countryURL:countryURL){ (result,error) in 
  if let res = result {
    print(res)
  } 
}