我正在尝试将JSON解析为数组。根据最高预约进行排序。然后使用该新数组在排行榜tableview上填充它。
我正在使用SwiftJson 坚持排序到数组
需要以降序的形式填充表格中的名称和其余值。
以下是我的摘要。
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()
以下是输出
{
"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"
}
}
}
答案 0 :(得分:0)
您可以将所有值作为字典数组并将其排序为:
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)
//为您的数据建模
for item in sorted {
let model = Model.init(jsonData: item)
// use 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
}
}
答案 1 :(得分:-1)
使用JsonSerialisation jsonObjectWithData将jSon响应转换为NSArray对象。并运行for循环,访问数组中的每个元素作为NSDictionary,并比较它们的值以获得最高约会。
要了解有关从NSDictionary访问值的更多信息,请apple docs reference
要了解有关在swift中使用json的更多信息,apple docs reference。
答案 2 :(得分:-1)
我尝试过这种排序:
let activitiesDict = jsonData?["Activities"] as? [String:Any]
let activitiesArray = activitiesDict.map({ [$0.0 : $0.1] })
let sortedActivitiesArray = self.activitiesArray.sorted {
(Int((($0 as! Dictionary<String, Any>)["Appointment Made"] as? String)!))! > (Int((($1 as! Dictionary<String, Any>)["Appointment Made"] as? String)!))!
}
print(sortedActivitiesArray)
希望它有所帮助。