How to use swiftyjson to parse json data to foundation object and loop through data

我与影子孤独终老i 提交于 2019-12-11 12:29:28

问题


So I'm trying to get his raw json data and use it to ultimately be viewed in a table(so one table cell would be --> Emirates - $1588.77)

Problem: Having trouble parsing the JSON data.. alamofire apparently does it automatically? but im completely confused with the data types. I keep getting weird errors like 'doesnt have a member named subscript" (I've also got swiftyjson installed but aa non-swiftyjson solution should work as well.

Code:

    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";
        }
    );
};

}


-------- Edit.


Using this model.

class FlightDataModel {
    var carrier: String
    var price: String

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

How woudl I use your solution to add it to an array of FlightDataModel class

This my my attempt..

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:


Alamofire can do it, but you have to dig into your JSON structure. :)

Like this, using Alamofire's responseJSON method:

    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))
                    }
                }
            }
        }
    }

Output:

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

It's a bit easier with SwiftyJSON indeed. And for diversity's sake, we'll use Alamofire's responseString method this time:

    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!)
            }
        }

    })

Output:

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

Note: I've used enumerate as an example for how getting the index of the content at the same time you get the content.



来源:https://stackoverflow.com/questions/30123657/how-to-use-swiftyjson-to-parse-json-data-to-foundation-object-and-loop-through-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!