如何使用swiftyjson将json数据解析为基础对象并循环遍历数据

时间:2015-05-08 12:16:39

标签: swift alamofire swifty-json

所以我试图获取他的原始json数据并最终在表中查看(因此一个表格单元格将是 - > Emirates - $ 1588.77)

问题:在解析JSON数据时遇到问题.. alamofire显然会自动执行此操作吗?但我完全混淆了数据类型。我不断得到奇怪的错误,比如'没有一个名为下标的成员'(我也安装了swiftyjson但是非swiftyjson解决方案应该也能正常工作。

代码:

    request(qpxRequest).responseJSON { (request, response, json, error) -> Void in
        if response != nil {
           //println(response!)
        }
        if json != nil {


          // 1. parse the JSON data into a Foundation object
         // 2. Grab the data from the foundation object (so its can be looped though      in a table)

}

{
trips =     {
    data =         {
        carrier =             (
                            {
                name = "Cathay Pacific Airways Ltd.";
            },
                            {
                name = Emirates;
            },
                            {
                name = "Ethiopian Airlines Enterprise";
            },
                            {
                name = "Qantas Airways Ltd.";
            },
                            {
                name = "South African Airways";
            }
        );
    };
    tripOption =         (
                    {
            saleTotal = "AUD1537.22";
        },
                    {
            saleTotal = "AUD1588.77";
        },
                    {
            saleTotal = "AUD1857.42";
        },
                    {
            saleTotal = "AUD1857.42";
        },
                    {
            saleTotal = "AUD1922.42";
        }
    );
};

}

--------编辑。

使用此模型。

class FlightDataModel {
    var carrier: String
    var price: String

    init(carrier: String?, price: String?) {
        self.carrier = carrier! 
        self.price = price!
    }
}

我如何使用您的解决方案将其添加到FlightDataModel类的数组

这是我的尝试..

var arrayOfFlights : [FlightDataModel] = [FlightDataModel]()



 if let tripOptions = trips["tripOption"] as? [[String:AnyObject]] {
                        for (index, tripOption) in enumerate(tripOptions) {
                            //println("\(index): " + (tripOption["saleTotal"]! as String))

                            self.arrayOfFlights[index].carrier = tripOption["saleTotal"]! as String


                            println("\(self.arrayOfFlights[index].carrier)")
                        }

1 个答案:

答案 0 :(得分:1)

Alamofire可以做到,但必须深入研究你的JSON结构。 :)

像这样,使用Alamofire的responseJSON方法:

    Alamofire.request(.GET, YOUR_URL, parameters: nil, encoding: .URL).responseJSON(options: NSJSONReadingOptions.allZeros) { (request, response, json, error) -> Void in
        if let myJSON = json as? [String:AnyObject] {
            if let trips = myJSON["trips"] as? [String:AnyObject] {
                if let data = trips["data"] as? [String:AnyObject] {
                    if let carriers = data["carrier"] as? [[String:String]] {
                        for (index, carrierName) in enumerate(carriers) {
                            println("\(index): " + carrierName["name"]!)
                        }
                    }
                }
                if let tripOptions = trips["tripOption"] as? [[String:AnyObject]] {
                    for (index, tripOption) in enumerate(tripOptions) {
                        println("\(index): " + (tripOption["saleTotal"]! as! String))
                    }
                }
            }
        }
    }

输出:

0: Cathay Pacific Airways Ltd.
1: Emirates
...
0: AUD1537.22
1: AUD1588.77
...

使用SwiftyJSON确实更容易一些。为了多样性,这次我们将使用Alamofire的responseString方法:

    Alamofire.request(.GET, YOUR_URL, parameters: nil, encoding: .URL).responseString(encoding: NSUTF8StringEncoding, completionHandler: {(request: NSURLRequest, response: NSHTTPURLResponse?, responseBody: String?, error: NSError?) -> Void in

        if let dataFromString = responseBody!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
            let json = JSON(data: dataFromString)
            let carriers = json["trips"]["data"]["carrier"].array
            for (index, carrier) in enumerate(carriers!) {
                println("\(index):" + carrier["name"].string!)
            }
            let tripOption = json["trips"]["tripOption"].array
            for (index, option) in enumerate(tripOption!) {
                println("\(index):" + option["saleTotal"].string!)
            }
        }

    })

输出:

0: Cathay Pacific Airways Ltd.
1: Emirates
...
0: AUD1537.22
1: AUD1588.77
...

注意:我已使用enumerate作为获取内容的同时获取内容索引的示例。