gpt4 book ai didi

ios - 如何将数据附加到来自 swift 3 中服务器响应的字典中?

转载 作者:行者123 更新时间:2023-11-30 12:02:36 24 4
gpt4 key购买 nike

这里我收到了来自服务器数据的响应,但在这里我需要在运输方法部分中显示如下图所示,在此承运人标题中将有子方法,其中需要在部分和部分中显示行数标题载体标题将被命名,这里方法标题需要从具有相同名称的特定载体标题附加到任何人都可以帮助我如何实现这个?

我已经尝试过的代码是

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
}

关于ios - 如何将数据附加到来自 swift 3 中服务器响应的字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47027791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com