ios - 无法解析数据 JSON alamofire SwiftyJSON

标签 ios json swift alamofire xcode8

尝试使用来自 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
    }    
}

Controller shown with Product List[1]

Debugger shown variable productlist was indeed append with value ] 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/

相关文章:

ios 撤消管理器 - 重置为第一个撤消

ios - UITableView didSelectRowAtIndexPath 选择多个单元格故障?

json - Dart:尽管强制转换,但仍无法将 List<dynamic> 转换为 List<Map<String, dynamic>>

python - 将 JSON 插入 MySQL

Swift:equatable 字典不能传递给泛型函数

ios - 两个动态 SCNNode 不发生碰撞 (Scenekit)

ios - 解析 JSON 数据

python - 使用 object_hook 将 JSON 字典解析为对象的奇怪行为

arrays - 多个数组提供 UICollectionView 数据源

ios - iOS 上像素完美的验收测试