[英]How to convert the response got from a server from string to array in swift 3?
在這里,在成功發布參數之后,我得到了響應,我需要將其取回,但是我遇到的問題是,我已經將數據保存在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()
}
您正在將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))")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.