Xan Xan - 28 days ago 9
Swift Question

How do i parse JSON, sort it in an array. Pull out the data and populate to a tableview?

i am trying to parse JSON into an array. Sort it according the highest appointment made. And then use that new array to populate it on leaderboard tableview.

I am using SwiftJson
Stuck on sorting into array

Would need to populate Name and the rest of the values in tableview in descending order.

Here are my snippets.

let jsonUrl = URL(string: url)
URLSession.shared.dataTask(with: jsonUrl!) { (data, response, error) in
guard let data = data else { return }
let jsonResult : JSON = JSON(data)
print(jsonResult)


} .resume()


Here are the output

{
"Activities" : {
"AHiHr9bzGXcN7pxvR68wulD9zqE3" : {
"Case Closed" : "2",
"Name" : "Tim Mac",
"Appointment Made" : "2",
"Prospects Met" : "2",
"Policy Servicing" : "2"
},
"gDKBlbeMsiUUFaASOLn6eOdCIrJ3" : {
"Case Closed" : "1",
"Name" : "Jane Simpson",
"Appointment Made" : "1",
"Prospects Met" : "1",
"Policy Servicing" : "1"
},
"W8uWoLf9qRX4a9BgXjLw5VZXjFu1" : {
"Case Closed" : "3",
"Name" : "John Doe",
"Appointment Made" : "4",
"Prospects Met" : "3",
"Policy Servicing" : "2"
}
}
}

Answer Source

you can get all values as Array of Dictionary and Sort it Like :

  guard let Activities = jsonResult?["Activities"] as? [String:AnyObject] else {
            return
        }

        var values = [Dictionary<String, AnyObject>]()

        for (_, value) in Activities {
            values.append(value as! Dictionary<String, AnyObject>)
        }


        let sorted =   values.sorted { (dic1, dic2) -> Bool in

            Int(dic1["Appointment Made"] as? String ?? "") ?? 0 > Int(dic2["Appointment Made"] as? String ?? "") ?? 0

        }

        print(sorted)

// model your data

 for item in sorted {

            let model = Model.init(jsonData: item)

            // use model
        }

// your model

class Model: NSObject {

    var caseClosed :Int?
    var name :String?
    var appointmentMade :Int?
    var prospectsMet :Int?
    var policyServicing :Int?



    override init() {
        super.init()
    }

    init(jsonData : [String:AnyObject]) {

        //  map data to object

    }
}