2017-02-04 78 views
1

尝试使用alamofire解析示例JSON对象,并且使用http中的SwiftlyJSON解析数据时遇到了麻烦,无法将其解析为我的产品模型。这真的很奇怪,我在for循环中运行了调试器,我迭代并执行“po self.productlist”,该值确实附加到数组中。但是,当我尝试在循环外打印时,它不起作用,当我尝试在调试器模式下执行“po self.productlist [0] [”product“]时也是如此。它在工作中的某一点真的很奇怪。正如你所看到的,我在imgur链接下面附加了2张图片。无法解析数据JSON alamofire SwiftJSON

我也附加了我的控制器和模型,我不知道我做了什么错误,或者可能有错误。任何帮助,将不胜感激。由于

控制器

import UIKit 
import Alamofire 
import SwiftyJSON 

class AddProductController: UITableViewController { 
    var productlist = [Product]() 


    override func viewDidLoad() { 
     super.viewDidLoad() 

     Alamofire.request("https://api.myjson.com/bins/1f1zop").responseJSON { response in 
      let jsondata = JSON(data: response.data!) 
      for index in 0..<jsondata["data"].count{ 

       self.productlist.append(Product(id: jsondata["data"][index]["id"].stringValue, product: jsondata["data"][index]["product"].stringValue, category: jsondata["data"][index]["category"].stringValue, price: jsondata["data"][index]["price"].doubleValue)) 
      } 
     } 
     print(self.productlist[0]["id"]) 

型号

import Foundation 

class Product { 
    var id:String 
    var product:String 
    var category: String 
    var price: Double 


    init(id:String, product:String, category:String, price:Double) { 
     self.id = id 
     self.product = product 
     self.category = category 
     self.price = price 
    }  
} 

Controller shown with Product List[1]

Debugger shown variable productlist was indeed append with value] 2

更新到vadian 谢谢,我明白了!

回答

0

没有错误,这就是着名的异步陷阱

Alamofire请求异步工作,JSON返回print行。

只需将print行(以及处理数组的代码)放入完成块。

发生此错误,因为您尝试像字典一样获得id。使用属性.id

顺便说一句:请不要在斯威夫特

Alamofire.request("https://api.myjson.com/bins/1f1zop").responseJSON { response in 
     let jsondata = JSON(data: response.data!) 
     for product in jsondata["data"].array! { 
      self.productlist.append(Product(id: product["id"].stringValue, product: product["product"].stringValue, category: product["category"].stringValue, price: product["price"].doubleValue)) 
     } 
     print(self.productlist[0].id) // use the property, it's not a dictionary. 
    } 

注意使用基于指数的循环:如果JSON是从第三方服务加载的,你应该使用可选的绑定解析数据安全。

+0

啊我其实已经尝试了for循环,就像你所做的一样,但我无法得到它的工作,可能错过了“.array!” 此外,感谢它现在能够打印。但我的主要目标是从alamofire codeblock获取数据,所以我可以将数据传输到其他地方,例如tableview数据源等。这是否意味着我只能在该代码块内进行限制?对不起,如果它听起来有点noob,我是非常新的ios编程,任何工作或建议从这里获取这些数据。 – Leo

+0

异步思考。只需在块内写入要执行的代码,例如将数组分配给数据源数组并重新加载表视图。但考虑在主线程上分派影响UI的代码。 – vadian