json - 在 swift 中使用字典和 utf-8 进行发布请求
问题描述
我需要发出一个发布请求,以在需要用 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
谢谢。
解决方案
你可以使用这个 Alamofire 方法
mydict = [:] // Your parameters here
if let theJSONData = try? JSONSerialization.data(
withJSONObject: mydict,
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .ascii)
multipartFormData.append((theJSONText?.data(using: .utf8)!)!, withName: "bulkData")
}
推荐阅读
- mysql - 检查 mariadb 是否可以连接,如果不能则修复
- c++ - UE4 C++ SpawnParams.Template->GetOwner() 不断返回 null
- python - Python中的异步套接字接收器
- c++ - 如何使用数字索引转换可变 std::tuple 的所有元素?
- angular - Primeng 数据表 - 调整窗口大小时列标题溢出单元格
- r - 如何在 group_by (dplyr) 中使用 paste?
- r - 如何在 lapply 中动态命名文件?
- c - 不使用 * operator hack-y 方式获取产品
- css - 我可以修改 Jupyter Lab 降价标签中使用的默认 CSS 样式吗?
- php - php 8.0 更新不从 httpd 解析