【问题标题】:Trouble parsing data JSON alamofire SwiftJSON无法解析数据 JSON alamofire SwiftyJSON
【发布时间】: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


    【解决方案1】:

    没有错误,这就是著名的async-trap

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

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

    发生错误是因为您尝试像字典一样获取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 是从第三方服务加载的,您应该使用可选绑定来安全地解析数据。

    【讨论】:

    • 啊,我确实尝试过像你所做的那样的 for 循环,但我无法让它工作,可能错过了“.array!”另外,谢谢它现在可以打印了。但我的主要目标是从 alamofire 代码块中获取数据,因此我可以将数据传输到其他地方,例如 tableview 数据源等。这是否意味着我只能限制在该代码块内?抱歉,如果这听起来有点菜鸟,我对 ios 编程很陌生,有任何解决方法或建议将这些数据从这里取出。
    • 异步思考。只需在块内编写要在块外执行的代码,例如将数组分配给数据源数组并重新加载表视图。但考虑在主线程上调度影响 UI 的代码。
    猜你喜欢
    • 1970-01-01
    • 2018-11-12
    • 2016-09-30
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多