swift:Alphabetiz数据是从JSON解析的

时间:2016-11-22 05:08:59

标签: ios json swift sorting swift2

我在Swift2中编写了自己的函数来解析JSON。解析JSON后,从JSON中提取的数据列表将显示在我的应用程序的sort中。我试图弄清楚如何按字母顺序显示这些数据。我认为这需要在我在函数中调用的append方法之前的某个地方发生。我想这需要一个 func parseJSON(){ do{ let data = NSData(contentsOfURL: NSURL(string: "https://jsonblob.com/api/jsonBlob/580d0ccce4b0bcac9f837fbe")!) let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) for anItem in jsonResult as! [Dictionary<String, AnyObject>]{ let mifiName2 = anItem["name"] as! String let mifiId = anItem["employeeId"] as! Int let newName = Name(mifiName: mifiName2, mifiId: mifiId) nameOfMifi.append(newName) //print("Name: \(newName)") } } catch let error as NSError{ print(error.debugDescription) } } 函数,但我无法找到正确执行此操作的Swift2中的正确排序函数。我能得到的任何帮助表示赞赏! 这是我的parseJSON函数:

include

1 个答案:

答案 0 :(得分:1)

sort中的所有对象append表示在Array循环之后,您需要for数组。

for anItem in jsonResult as! [Dictionary<String, AnyObject>]{

    let mifiName2 = anItem["name"] as! String
    let mifiId = anItem["employeeId"] as! Int

    let newName = Name(mifiName: mifiName2, mifiId: mifiId)
    nameOfMifi.append(newName)
    //print("Name: \(newName)")
}

//Now you need to sort your array on the basis of name like this
nameOfMifi.sortInPlace { $0.mifiName < $1.mifiName } 

修改:@vadian建议不要使用NSData(contentsOfURL:)因为它会阻止您的用户界面,所以要像这样使用NSURLSession

let session = NSURLSession.sharedSession()
let url = NSURL(string: "https://jsonblob.com/api/jsonBlob/580d0ccce4b0bcac9f837fbe")!
var task = session.dataTaskWithURL(url, completionHandler: {
    (data, response, error) -> Void in
    if error != nil {
        return
    }

    if let jsonResult = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? [Dictionary<String, AnyObject>] {

        for anItem in jsonResult {

            let mifiName2 = anItem["name"] as! String
            let mifiId = anItem["employeeId"] as! Int

            let newName = Name(mifiName: mifiName2, mifiId: mifiId)
            nameOfMifi.append(newName)
            //print("Name: \(newName)")
        }
        //Now you need to sort your array on the basis of name like this
        nameOfMifi.sortInPlace { $0.mifiName < $1.mifiName } 

        //Now reload tableView on main thread.
        dispatch_async(dispatch_get_main_queue()) {
             self.tableView.reloadData()
        }
    }
})
task.resume()