【发布时间】:2017-02-04 14:11:41
【问题描述】:
尝试使用来自 http 的 alamofire 和 SwiftlyJSON 解析示例 JSON 对象时遇到了麻烦,无法将其解析为我的产品模型。真的很奇怪,我在 for 循环中运行调试器,我迭代并执行“po self.productlist”,该值确实被附加到数组中。但是当我尝试在循环之外打印它时,它就不起作用了,当我尝试在调试器模式下执行“po self.productlist [0] [“product”]”时也是如此。有一点它在起作用真的很奇怪。如您所见,我在 imgur 链接中附上了下面的 2 张图片。
我还附上了我的控制器和模型,我不确定我犯了什么错误,或者可能存在错误。任何帮助,将不胜感激。谢谢
控制器
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 谢谢我明白了!
【问题讨论】:
标签: ios json swift alamofire xcode8