Alamofire:Unicode字符被添加额外斜杠问题
解决Alamofire响应转NSDictionary时Unicode字符出现额外斜杠的问题
我之前也碰到过类似的情况,其实大部分时候你看到的额外斜杠只是控制台打印的转义显示效果,并不是实际存储的字符有问题,不过还是可以通过调整解析方式来确保字符正常处理。下面是具体的解决思路和修正代码:
先搞清楚问题根源
当你直接打印NSDictionary或者未处理的JSON值时,系统会对Unicode字符做转义输出(比如把₹显示成\u{20b9},甚至在某些场景下会多一层斜杠变成\\u{20b9}),但实际字符串中的字符是完全正常的——你把这个值放到UI上显示,或者直接使用字符串内容时,额外的斜杠会自动消失。
修正后的代码方案
推荐用SwiftyJSON来处理解析(你代码里已经提到了SwiftyJSON,但没充分利用它的优势),这样能更稳妥地处理Unicode字符:
Alamofire.request("MyURL", method: .post, parameters: attributes, encoding: URLEncoding.default, headers: [:]) .responseJSON { response in switch response.result { case .success(let rawValue): // 用SwiftyJSON封装原始响应值 let json = JSON(rawValue) // 1. 直接获取字符串值,验证Unicode字符 if let targetString = json["your_target_key"].string { print("实际字符串内容:\(targetString)") // 这里不会有额外斜杠 // 比如如果是金额,直接显示在Label上: // yourLabel.text = targetString } // 2. 如果确实需要转成NSDictionary if let dicObj = json.dictionaryObject as NSDictionary? { let valueFromDic = dicObj["your_target_key"] ?? "" print("NSDictionary中的值:\(valueFromDic)") } case .failure(let error): print("请求出错:\(error.localizedDescription)") } }
特殊情况:服务器返回的JSON本身带转义
如果服务器返回的响应字符串本身就包含转义的斜杠(比如返回的是"amount": "\\u20b9100"),那你需要先对字符串做一次转义处理,再解析:
Alamofire.request("MyURL", method: .post, parameters: attributes, encoding: URLEncoding.default, headers: [:]) .responseString { response in switch response.result { case .success(let responseString): // 去除多余的转义斜杠 let unescapedString = responseString.replacingOccurrences(of: "\\\\u", with: "\\u") guard let data = unescapedString.data(using: .utf8) else { return } do { if let dicObj = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary { print(dicObj["your_target_key"] ?? "") } } catch { print("解析失败:\(error)") } case .failure(let error): print("请求出错:\(error.localizedDescription)") } }
额外提醒
尽量避免用!强制解包response.result.value,一旦响应格式不符合预期,很容易导致崩溃——用可选绑定(if let/guard let)处理更安全。
内容的提问来源于stack exchange,提问作者Sarabjit Singh
相关产品推荐
相关产品推荐

