How to Sort JSON Coming from Alamofire and Return Final JSON Object (Swiftyjson)

How to sort JSON coming from Alamofire and return final JSON object (swiftyJSON)

If results is a SwiftyJSON object, you can extract its array with .arrayValue.

let resultsArray = results.arrayValue

Then once you have a normal array of dictionaries, you can then sort the array with sort like this:

let sortedResults = resultsArray.sort { $0["distance"].doubleValue < $1["distance"].doubleValue }

I took your JSON snippet:

Sample Image

And tested my answer in a Playground with SwiftyJSON:

Sample Image


If you wanted to, you could also sort the SwiftyJSON object directly:

let sortedResults = results.sort { $0.0.1["distance"].doubleValue < $0.1.1["distance"].doubleValue }.map { $0.1 }

But I find it less readable as source code.

Sorting JSON when using Alamofire and SwiftyJSON

Since you have a NSDate property, you can sort with the compare method of NSDate.

let sorted = result.value.sort { $0.date.compare($1.date) == .OrderedAscending }

Error using Alamofire/SwiftyJSON in swift 4.0

No, they didn't cause the problem.

JSON() expects a data input, but you are passing nothing than a name.

You have to call Alamofire for creating data as a response of your server request and pass this response data to your JSON variable.

But you can't call a function inside a class definition anyways.

Please read the documentation of Alamofire, SwiftyJSON and a guide to Swift/iOS programming.

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

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.

How can I grab the correct JSON response using SwiftyJSON?

Check out this code:

let url = "Foursquare Venue Detail API request goes here"
Alamofire .request(.GET, url) .responseJSON(options: nil) { (_, _, data, error) -> Void in
if error != nil {
println(error?.localizedDescription)
} else if let data: AnyObject = data {
let jObj = JSON(data)
if let venue = jObj["response"]["venue"].dictionary {
println(venue)
}

}
}

So the main difference here is that the data is a dict, not an array.

By the way, consider reloading the table view in the main queue as this affects the UI:

dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData() // Update UI
}

Converting JSON from AlamoFire/SwiftyJSON to Dictionary in Swift/Xcode

Oh you were so close!

Your problem is that your post dictionary is a [String: String] and not an [Int: String] like you think it is. You have a few ways to fix it, but the easiest for now would be to just do the following:

let locationID = post[String(closestBeacon.minor.integerValue)]!

While this will certainly work, a better solution would be to convert your post into a [Int: String] typed dictionary like you expect in the responseJSON closure. Here's how this could work.

let json = JSON(data)
var post = [Int: String]()

for (key, object) in json {
post[key.toInt()!] = object.stringValue
}

You would want to add some safety around what to do if the key or object were not able to be converted to an Int or String respectively, but I'll leave that to you.



Related Topics



Leave a reply



Submit