【问题标题】:Can not get Json data with Alamofire Swift无法使用 Alamofire Swift 获取 Json 数据
【发布时间】:2015-09-13 07:21:15
【问题描述】:

我尝试从网站获取 json 数据,但是,我可以通过以下方式访问 json 数据。

   { 
  "product_categories":[ 
     {    
     "id":27,
     "name":"Clothing",
     "slug":"product-categories-1",
     "parent":0,
     "description":"",
     "count":3
   }
  ]
} 

另一方面,当我尝试如下获取 json 数据时,

   { 
     "product":{ 
     "title":"Night Cream",
     "id":4573,
     "created_at":"2015-08-21T07:54:09Z",
     "updated_at":"2015-08-27T01:37:06Z",
    }

 }

jason 数据响应返回“[]”

我正在使用 Alamofire 获取数据。这是我的代码。

       Alamofire.request(.GET, url).responseJSON {
        (request, response, json, error) in

        if json != nil {


            var jsonObj = JSON(json!)

            if let data = jsonObj["product"].arrayValue as [JSON]? {
                self.productsAll = data
                self.collectionView!.reloadData()

            }

如何获取所有产品数据。请指教。谢谢。

【问题讨论】:

  • 在第一种情况下,您一直在 json 数组中,而在第二种情况下,json 中只有一个字典,但是您试图获取一个带有 jsonObj["product"].arrayValue as [JSON]? 的数组,并且它是空的,因为那里json 中没有数组类型。在这种情况下,您需要像普通字典一样访问数据
  • 试试这个:if let data = jsonObj["product"] as! [NSDictionary]
  • 感谢您的建议。我已经尝试过了,但它仍然无法正常工作。从“JSON”转换为不相关类型“NSDictionary”总是失败

标签: json xcode swift alamofire


【解决方案1】:

您正在尝试将 json 对象转换为 json 数组,这意味着您的条件展开将永远不会执行。

替换

if let data = jsonObj["product"].arrayValue as [JSON]? {
    self.productsAll = data
    self.collectionView!.reloadData()
}

if let data = jsonObj["product"].dictionaryObject {
    // since self.productsAll seems to be an array, append the product to the array or rebuild the array before calling self.collectionView!.reloadData()
}

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多