我需要发出发布请求,以便在发布请求的正文中发送需要用utf-8编码的字典, 我在下面尝试了此方法,但它给出了一个错误:
let DicObject: NSMutableDictionary = NSMutableDictionary()
DicObject.setValue("cf", forKey: "a")
DicObject.setValue("", forKey: "scs")
DicObject.setValue("Uploads/" + nameOfFile, forKey:"p")
当我尝试制作
request.httpMethod = "POST"
// request.httpBody = jsonObject as Data
request.addValue("Content-Type", forHTTPHeaderField: "application/x-www-form-urlencoded; charset=utf-8")
它不起作用,有人知道如何将jsonObject
编码转换为utf-8
谢谢。
答案 0 :(得分:0)
您可以使用jsonObject
将data
转换为JSONSerialization
,然后将data
转换为string
,最后将string
转换为data
>
if let data = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted),
let jsonString = String(data: data, encoding: .utf8) {
request.httpBody = jsonString.data(using: .utf8)
}
答案 1 :(得分:0)
尝试一下,
let jsonData: NSData
do {
jsonData = try JSONSerialization.data(withJSONObject: DicObject, options: JSONSerialization.WritingOptions()) as NSData
let jsonString = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue)! as String
print("json string = \(jsonString)")
print("json jsonData = \(jsonData)")
} catch _ {
print ("JSON Failure")
}
谢谢!
答案 2 :(得分:0)
您可以使用这种Alamofire方法
T extends