【问题标题】:Json results to a string array in swiftJson 快速生成字符串数组
【发布时间】:2016-05-10 09:06:10
【问题描述】:

您好,我一直在尝试发出 json 请求,我想将它的一些结果放入字符串数组中。

所以我有以下代码

var arrRes = [[String:AnyObject]]()
var nameaRR = [String]()
override func viewDidLoad() {
    super.viewDidLoad()

    Alamofire.request(.GET, "https://graph.facebook.com/search", parameters: ["q": "", "type": "place", "center": "37.928319,23.7036673", "distance": "10000","limit": "1000", "access_token": "SomeToken", "expires_in": "5184000"])
        .responseJSON { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                let swiftyJsonVar = JSON(responseData.result.value!)
                //print(swiftyJsonVar)
                if let resData = swiftyJsonVar["data"].arrayObject {
                    self.arrRes = resData as! [[String:AnyObject]]


                    self.nameaRR = swiftyJsonVar["data"]["name"] as! [String]

                    print(self.nameaRR)

                }
                if self.arrRes.count > 0 {
                    self.kati.reloadData()
                }
            }

    }


}

JSON 结果如下

    {
      "data" : [
        {
          "category_list" : [
            {
              "id" : "272705352802676",
              "name" : "Outdoors"
            },
            {
              "id" : "115725465228008",
              "name" : "Region"
            }
          ],
          "id" : "552889064768971",
          "name" : "Παλαιο Φαληρο", //This String i want to put in an Array
          "category" : "Local business",
          "location" : {
            "street" : "",
            "city" : "Palaión Fáliron",
            "country" : "Greece",
            "longitude" : 23.6944070162,
            "zip" : "17562",
            "latitude" : 37.9284637008,
            "state" : ""
          }
        }
]
}

我收到警告
Cast from 'JSON' to unrelated type '[String]' always fails

但我不知道如何将所有字符串放入数组nameaRR。 谁能帮我找出我的错误?谢谢!

【问题讨论】:

  • 既然你已经取消了resData的引用,为什么不继续使用它而不是重复使用swiftyJsonVar?? name 不是数组。总是String
  • 这段代码有很多问题...最明显的是: 1. swiftyJsonVar["data"] 是一个数组,所以["data"]["name"] 无效(你的意思可能是获取第一项的数组和 then 抓取 name) & 2. 即使在检索到 name 之后,它也只是一个 String 而不是字符串数组 ([String]),这意味着它不能分配给nameaRR。我希望这是有道理的......

标签: swift swift2 alamofire swifty-json


【解决方案1】:

看起来像那样

if let resData = swiftyJsonVar["data"] as? [[String:AnyObject]] {
  if let categorylist = resData["category_list"] as? [[String:AnyObject]]{
    if let id =  categorylist["id"] as? Int{
   print(id)
}
} 
}

【讨论】:

    猜你喜欢
    • 2018-02-15
    • 2015-04-04
    • 2013-07-04
    • 2020-01-13
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多