【问题标题】:Why Alamofire 4.4.0 turns JSON string with escaped JSON string (Swift 3)?为什么 Alamofire 4.4.0 将 JSON 字符串转换为转义的 JSON 字符串(Swift 3)?
【发布时间】:2017-04-22 14:25:57
【问题描述】:

我在将 JSON 数据转换为字符串时遇到问题。

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)
}

日志: 原始字符串 -> http://10.1.10.98/POSSytem/api/inventories/PutInventory?received={'id':'coke','price':4.99,'In_stock':2}

DefaultDataResponse(请求:无,响应:无,数据:可选(0 字节),错误: 可选(Alamofire.AFError.invalidURL("http://10.1.10.98/POSSytem/api/inventories/PutInventory?received={\'id\':\'coke\',\'price\':4.99,\'In_stock\':2}")), 时间线:时间线:{“请求开始时间”:514563518.605,“初始 响应时间”:514563518.597,“请求完成时间”: 514563518.597,“序列化完成时间”:514563518.605,“延迟”:-0.007 秒,“请求持续时间”:-0.007 秒, “序列化持续时间”:0.007 秒,“总持续时间”:0.000 秒}, _metrics:无)

由于某种原因,Alamofire 将 url 变成了不同的 url。在 JSON 字符串中添加转义字符。阿拉莫火 4.4.0 它应该保持不变:"http://10.1.10.98/POSSytem/api/inventories/PutInventory?received={'id':'coke','price':4.99,'In_stock':2}"

【问题讨论】:

    标签: json post swift3 alamofire


    【解决方案1】:
    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)
        }
    

    使用后

    添加百分比编码

    它为有效的 url 编码了 JSON 字符串,并触发了 post 调用。

    【讨论】:

      最近更新 更多