尝试使用来自 http 的 alamofire 和 SwiftlyJSON 解析示例 JSON 对象时,无法将其解析为我的产品模型。这真的很奇怪,我在 for 循环中运行调试器,我迭代并执行“po self.productlist”,该值确实被附加到数组中。但是当我尝试在循环外打印它时,它不起作用,当我尝试在调试器模式下执行“po self.productlist[0][“product”]”时也是如此。它在某一时刻起作用真的很奇怪。如您所见,我在 imgur 链接中附上了下面的 2 张图片。
我还附加了我的 Controller 和模型,我不确定我做错了什么,或者可能有错误。任何帮助,将不胜感激。谢谢
Controller
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
}
}
] 2
vadian 更新 谢谢,我明白了!
最佳答案
没有错误,这就是著名的异步陷阱。
Alamofire 请求异步工作,JSON 在 print
行之后返回。
只需将 print
行以及处理数组的代码放入完成 block 中。
错误发生,因为你试图像字典一样获取id
。使用属性 .id
顺便说一句:请不要在 Swift 中使用基于索引的循环
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 是从第三方服务加载的,您应该使用可选绑定(bind)来安全地解析数据。
关于ios - 无法解析数据 JSON alamofire SwiftyJSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42041329/