![](/img/trans.png)
[英]SWIFT: Retrieve data from Parse and append it to a key value dictionary
[英]How to append the data to dictionary coming from server response in swift 3?
在这里,我收到服务器数据的响应,但是在这里,我需要显示如下运输方法部分中的图像所示,在此承运人标题中将包含子方法,在该子方法中,该子方法需要按节中的行数显示,并显示节标题承运人标题将被命名,并且此处的方法标题需要从具有相同名称的特定运营商标题中追加,任何人都可以帮助我实现该方法吗?
我已经尝试过的代码是
var doubleRemoving : [String:Any] = [:]
do
{
let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String : Any]]
self.responseData = array!
print(self.responseData)
}
catch let error
{
print("json error:", error)
}
for item in self.responseData {
let dict = item
let array = dict["carrier_title"]
self.keyString.append(array as! String)
self.doubleRemoving.updateValue(0, forKey: array as! String)
print(self.doubleRemoving)
}
for item in self.responseData{
if self.doubleRemoving.keys.contains(item["carrier_title"] as! String) {
self.doubleRemoving.updateValue(item["method_title"]!, forKey: item["carrier_title"] as! String)
}
print(self.doubleRemoving)
}
let status = (response as! HTTPURLResponse).statusCode
self.keyStatusCode = status
print(status)
}
task.resume()
}
来自服务器的Json响应是
[
{
"carrier_code": "flatrate",
"method_code": "flatrate",
"carrier_title": "Flat Rate",
"method_title": "Fixed",
"amount": 0,
"base_amount": 0,
"available": true,
"error_message": "",
"price_excl_tax": 0,
"price_incl_tax": 0
},
{
"carrier_code": "tablerate",
"method_code": "bestway",
"carrier_title": "Best Way",
"method_title": "Table Rate",
"amount": 0,
"base_amount": 0,
"available": true,
"error_message": "",
"price_excl_tax": 0,
"price_incl_tax": 0
},
{
"carrier_code": "tablerate",
"method_code": "bestway",
"carrier_title": "Best Way",
"method_title": "Worldwide Expedited",
"amount": 0,
"base_amount": 0,
"available": true,
"error_message": "",
"price_excl_tax": 0,
"price_incl_tax": 0
},
{
"carrier_code": "tablerate",
"method_code": "bestway",
"carrier_title": "Best Way",
"method_title": "Worldwide Express Saver",
"amount": 0,
"base_amount": 0,
"available": true,
"error_message": "",
"price_excl_tax": 0,
"price_incl_tax": 0
}
]
你可以做这样的事情
var finalDict = [String: [String]]()
let array = try JSONSerialization.jsonObject(with: getData()!, options: []) as! NSArray
for item in array {
let dict = item as! NSDictionary
let carrierTitle = dict["carrier_title"] as! String
let methodTitle = dict["method_title"] as! String
if finalDict[carrierTitle] == nil {
finalDict[carrierTitle] = [String]()
}
finalDict[carrierTitle]!.append(methodTitle)
}
输出量
["Flat Rate": ["Fixed"], "Best Way": ["Table Rate", "Worldwide Expedited", "Worldwide Express Saver"]]
更新
要获取所有值的计数,请执行以下操作
var count = 0
for (key, value) in finalDict {
count += value.count
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.