2017-04-22 157 views
0

我有問題將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

回答

0
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調用。