为什么Alamofire 4.4.0将JSON字符串转义为JSON字符串(Swift 3)?
我有问题将JSON数据转换为字符串。为什么Alamofire 4.4.0将JSON字符串转义为JSON字符串(Swift 3)?
var url = "http://10.1.10.98/POSSytem/api/inventories/PutInventory?received={'id':'coke','price':4.99,'In_stock':2}"
print(url)
Alamofire.request(str, method: .post, parameters: [:], encoding: JSONEncoding, headers: nil)
.response { (res) in
print(res)
}
LOGS: original string ->http://10.1.10.98/POSSytem/api/inventories/PutInventory?received= {'id':'coke','price':4.99,'In_stock':2}
DefaultDataResponse(request: nil, response: nil, data: Optional(0 bytes), error: Optional(Alamofire.AFError.invalidURL(" http://10.1.10.98/POSSytem/api/inventories/PutInventory?received= {\'id\':\'coke\',\'price\':4.99,\'In_stock\':2}")), timeline: Timeline: { "Request Start Time": 514563518.605, "Initial Response Time": 514563518.597, "Request Completed Time": 514563518.597, "Serialization Completed Time": 514563518.605, "Latency": -0.007 secs, "Request Duration": -0.007 secs, "Serialization Duration": 0.007 secs, "Total Duration": 0.000 secs }, _metrics: nil)
出于某种原因Alamofire打开网址到不同的URL。在JSON字符串中添加转义字符。 alamofire 4.4.0 它应该留: “http://10.1.10.98/POSSytem/api/inventories/PutInventory?received= { '身份证': '可乐', '价格':4.99, 'IN_STOCK':2}” 使用
addingPercentEncoding
guard let js = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
print("Error parsing json data \(dict)")
return
}
let theJSONText = String(data: js,encoding: .ascii)
url += "\(theJSONText!)"
let finalURL = url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
Alamofire.request(finalURL!, method: .post)
.response { (res) in
print(res)
}
后它将JSON字符串编码为有效的url,并触发post调用。