Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 从JSON文件读取国家名称有问题_Ios_Json_Swift_Xcode - Fatal编程技术网

Ios 从JSON文件读取国家名称有问题

Ios 从JSON文件读取国家名称有问题,ios,json,swift,xcode,Ios,Json,Swift,Xcode,我正在尝试使用swift从json文件加载和解析国家名称,但我不能 这是我尝试读取的文件格式: 执行此任务的我的代码: func getJsonFromUrl(){ let url = NSURL(string: COUNTRIES_URL) URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in if le

我正在尝试使用swift从json文件加载和解析国家名称,但我不能

这是我尝试读取的文件格式:

执行此任务的我的代码:

func getJsonFromUrl(){
    let url = NSURL(string: COUNTRIES_URL)
    URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
            if let countries_array = jsonObj!.value(forKey: "name") as? NSArray {
                for country in countries_array {
                    if let countryDict = country as? NSDictionary {
                        if let name = countryDict.value(forKey: "name") {
                            self.countries_names.append((name as? String)!)
                        }
                    }
                }
            }
            OperationQueue.main.addOperation ({
                self.showNames()
            })
        }
    }).resume()
}
但是当我运行它时,它在这一行给了我一个错误:
if-let-countries\u-array=jsonObj!。值(forKey:“name”)为?NSArray{

因为意外的零。

这是一个数组,而不是您需要的字典

if let dat = data {
   if let jsonObj = try? JSONSerialization.jsonObject(with: dat, options:[]) as? [[String:String]]{
   jsonObj.forEach { print($0["name"]) }    
}
或者使用
Codable

let res = try? JSONDecoder().decode([[String:String]].self,from:data)
struct Country : Decodable {
    let name : String
}

func getJsonFromUrl() {
    let url = URL(string: COUNTRIES_URL)!
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in
        if let error = error { print(error); return }
        do {
            let countries = try JSONDecoder().decode([Country].self, from: data!)
            self.countries_names = countries.map{$0.name}
        } catch { print(error) }
        OperationQueue.main.addOperation ({
            self.showNames()
        })
    }).resume()
}
还是用模型

struct Root: Codable {
  let name : String
}

let res = try? JSONDecoder().decode([Root].self,from:data)

JSON以括号(
[
)开头,因此根对象是一个数组

不要在Swift中使用
NSURL
NSArray
NSDictionary
值(forKey

并处理可能出现的错误

func getJsonFromUrl() {
    let url = URL(string: COUNTRIES_URL)!
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in
        if let error = error { print(error); return }
        do {
            if let countriesArray = try JSONSerialization.jsonObject(with: data!) as? [[String:String]] {
                for country in countriesArray {
                    self.countries_names.append(country["name"]!)
                }
            }
        } catch { print(error) }
        OperationQueue.main.addOperation ({
            self.showNames()
        })
    }).resume()
}
或者使用可解码的
更方便

let res = try? JSONDecoder().decode([[String:String]].self,from:data)
struct Country : Decodable {
    let name : String
}

func getJsonFromUrl() {
    let url = URL(string: COUNTRIES_URL)!
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) -> Void in
        if let error = error { print(error); return }
        do {
            let countries = try JSONDecoder().decode([Country].self, from: data!)
            self.countries_names = countries.map{$0.name}
        } catch { print(error) }
        OperationQueue.main.addOperation ({
            self.showNames()
        })
    }).resume()
}

如果让jsonObj=try?JSONSerialization.jsonObject(带:data!,选项:.allowFragments)作为?NSDictionary,则行
{
应该是
as?Array
,因为最上面的对象实际上是一个Array,所以不要使用强制unwrapping@AdityaSrivastava在这种情况下,一切都非常安全。URL字符串是一个常量,
data
error
nil
且JSON一致的情况下有效。您甚至可以强制展开downcast到
[[String:String]]