如何对来自Alamofire的JSON进行排序并返回最终的JSON对象(swiftyJSON)

时间:2015-10-26 16:38:45

标签: swift alamofire swifty-json

我无法简洁地从api中提取数据,将用户当前位置添加到对象中,然后根据计算的距离对数据进行排序。

stackoverflow问题并不能解决我面临的问题。见这里:How to sort posts read from JSON server file in Swift

我目前正在从Alamofire加载api数据并使用UITableViewController渲染该数据。

    override func viewDidLoad() {
    super.viewDidLoad()
    titleLabel.title = q.capitalizedString
    Alamofire.request(.GET, "http://www.thesite.com/api/v1/things", parameters: ["q" : q])
        .responseJSON { response in
            let JSONObject = JSON(response.result.value!)
            self.results = JSONObject["things"]
            for (key, _) in self.results {
                let intKey: Int = Int(key)!
                var thisItem: JSON = self.results[intKey]
                let geoLat = thisItem["place"][0]["location"]["geo"][1].double ?? 37.763299
                let geoLong = thisItem["place"][0]["location"]["geo"][0].double ?? -122.419356
                let destination = CLLocation(latitude: geoLat, longitude: geoLong)
                let setLocation = CLLocation(latitude: self.currentLocation.latitude, longitude: self.currentLocation.longitude)
                let distanceBetween: CLLocationDistance = destination.distanceFromLocation(setLocation)
                thisItem["distance"].double =  distanceBetween
                self.results[intKey] = thisItem
            }
            self.tableView.reloadData()
    }
}

我从api获取数据并成功添加用户位置和地点目的地之间的距离。

但是,现在我需要从最低到最高距离对JSON对象(SwiftyJSON)进行排序。这就是我被困住的地方。

重新加载tableView(作为JSON对象)时的数据结构基本上是:

results = [
{"title": "Chai", "distance": "1245.678575"},
{"title": "Espresso", "distance": "765845.678575"},
{"title": "Drip Coffee", "distance": "23445.678575"}
...
]

我如何能够:1)将对象转换为NSArray并进行排序;或2)只是排序对象?什么时候做距离添加和排序的最佳位置 - 我应该在转换为JSON对象之前进行。

任何帮助表示赞赏!谢谢!

3 个答案:

答案 0 :(得分:10)

如果results是SwiftyJSON对象,则可以使用.arrayValue提取其数组。

let resultsArray = results.arrayValue

然后,一旦你有一个正常的字典数组,你就可以用sort对这个数组进行排序:

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

我带了你的JSON片段:

enter image description here

使用SwiftyJSON在Playground中测试了我的答案:

enter image description here

如果您愿意,还可以直接对SwiftyJSON对象进行排序:

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

但我发现它作为源代码的可读性较差。

答案 1 :(得分:0)

斯威夫特3&amp;斯威夫特4

let sortedResults = finalJsonArray.sorted { $0["count"].doubleValue < $1["count"].doubleValue }

答案 2 :(得分:0)

Swift 3 + Swift 4 我发现的最短解决方案如下:

<按升序排序,
>正在按降序排序

排序(String,JSON)格式(使用SwiftyJSON时)非常有效

let sortedResults = json.sorted(by: < )