ios - JSON 数组中的这两行之间有什么不同,这意味着没有被识别?

标签 ios swift

我有一个 API 调用,它从我的数据库中检索包含国家部门团队的数组。

此输出显示了在 Swift 中接收时 JSON 的格式(示例中未显示teams:

Optional(["countries": <__NSArrayI 0x6180001f6500>( { id = 1; name = Denmark; }, { id = 2; name = Belgium; } ) , "divisions": <__NSArrayI 0x7fc8a34455a0>( { Name = "ALKA SUPERLIGA"; "country_id" = 1; id = 1; }, { Name = "PRO LEAGUE"; "country_id" = 2; id = 2; }

我在 swift 中使用以下函数将 countriesdivisions 排序到不同的字符串数组中,然后在 UITableView 中使用。

    override func viewDidAppear(_ animated: Bool) {
    let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getTeams.php?");
    var request = URLRequest(url:myUrl!);
    request.httpMethod = "POST";
    let postString = "";

    request.httpBody = postString.data(using: String.Encoding.utf8);

    let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

        DispatchQueue.main.async
            {

                if error != nil {
                    print("error=\(error)")
                    return
                }

                do{
                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
                        print (json)

                        if let arr = json?["countries"] as? [[String:String]] {
                            self.countryId = arr.flatMap { $0["id"]!}
                            self.countries = arr.flatMap { $0["name"]!}
                            self.teamsTableView.reloadData()
                            print ("Countries: ",self.countries)
                        }

                    if let arr = json?["divisions"] as? [[String:String]] {

                        self.divisions = arr.flatMap { $0["Name"]!}
                        self.divisionId = arr.flatMap { $0["id"]!}
                        self.teamsTableView.reloadData()
                        print ("Divisions: ",self.divisions)
                    }



                } catch{
                    print(error)
                }
        }
    }
    task.resume()
    //membersTableView.reloadData()

}

print ("Countries: ",self.countries) 按预期输出,如下:

Countries: [Optional("Denmark"), Optional("Belgium")

但是 print ("Divisions: ",self.divisions) 甚至没有运行。因此,该 IF 命令肯定有问题,但我使用的代码与“国家/地区”部分中使用的代码相同。

有什么想法吗?

我尝试将 [[String : String]] 替换为 [[String : String?]] 但这没有任何作用。我也尝试过 [[String : Any]] 但这在 arr.flapMap 行上带来了以下错误:

'(_) -> Any' to expected argument type '(Dictionary) -> SegmentOfResult'

最佳答案

首先,在 Swift 3 中,常见的未指定类型是 Any而不是AnyObject

在给定的 JSON 中

  • 根对象是 [String:Any]
  • divisions 的值是 [[String:Any]]因为它包含String<null>类型。

<null>将替换为 n/a

if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any] {
       print (json)

       if let arr = json["countries"] as? [[String:String]] {
          self.countryId = arr.flatMap { $0["id"]!}
          self.countries = arr.flatMap { $0["name"]!}
          self.teamsTableView.reloadData()
          print ("Countries: ",self.countries)
       }

       if let arr = json["divisions"] as? [[String:Any]] {
          self.divisions = arr.flatMap { $0["Name"] as? String ?? "n/a" }
          self.divisionId = arr.flatMap { $0["id"] as? String }
          self.teamsTableView.reloadData()
          print ("Divisions: ",self.divisions)
       }
} 

注释:

请勿不要将多个数组与 flatMap 结合使用作为数据源,这很容易出错,请改用自定义结构。

一个POST不需要请求,GET (传递 url 的数据任务)就足够了。

关于ios - JSON 数组中的这两行之间有什么不同,这意味着没有被识别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40341136/

相关文章:

ios - UICollectionViewCell 与 Storyboard

ios - 标签框未正确停留在 `UICollectionViewCell`

ios - 当主线程针对另一个调度队列发出 dispatch_sync 时,主队列/主线程会发生什么?

ios - 创建一个椰子

ios - 使用 Swift 3D 触摸力值改变声音的音量

ios - 访问 ios 照片并上传到网络服务器

ios - 针对 iOS7 优化应该怎么做?

iOS13 : NumberFormatter missing groupingSeparator when try to format 4 digits numbers with es_ES locale

swift - 如何在 Swift 应用程序中将操作链接到文件->保存/文件->打开

objective-c - UIColor 类不允许我实例化 UIColor。有关系吗? !符号