这里我成功发布参数后得到了响应,我需要将其检索回来,但问题是我卡在这里,我已经保存了responseString
中的数据,并且它以字符串的形式存储,当我尝试检索它并保存在一个无法保存的数组中任何人都可以帮助我如何保存并且数据格式如下
这是服务器响应
[
{
"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
}
]
这是发布参数的json函数
func shippingmethodURL(shippingMethodAPI:String) {
let url = NSURL(string: shippingMethodAPI)
var request = URLRequest(url: url! as URL)
request.httpMethod = "POST"
print(shippingMethodAPI)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let addtoCartVC = storyboard.instantiateViewController(withIdentifier: "checkout") as! CheckoutViewController
let parameters : [String: Any] = ["address":
[ "region": "California",
"region_code": "CA",
"region_id": "12",
"country_id": "US",
"company": "Test",
"telephone": "9492162752",
"postcode": "43",
"city": "Chennai",
"firstname": "gdfgdgdfg",
"lastname": "dgdfgdfgg",
"email": "sfdsfsdf@gmail.com",
"prefix": "",
"sameAsBilling": 1,
"street": ["Dsfdsfsd dfdsfdsf dsfsfdsfsf sdfsfdsfsdfC"]]]
print(parameters)
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
print(request)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let status = (response as! HTTPURLResponse).statusCode
self.keyStatusCode = status
print(status)
let array = responseString
}
task.resume()
}
答案 0 :(得分:3)
您正在将Data
转换为String
但是Array
您需要使用JSONSerialization
课程来实现此目标
您必须替换此代码
let responseString = String(data: data, encoding: .utf8)
与
let array = try JSONSerialization.jsonObject(with: data!) as? [[String : Any]]
修改强>
你需要把它放在像这样的do try catch
块中
do {
let array = try JSONSerialization.jsonObject(with: data) as? [[String : Any]]
} catch {
print("Exception occured \(error))")
}