在Swift中正确编码JSON主体以供HTTP请求
我正在尝试在JSON中编码键/值对,以在iOS 15上的Swift中为HTTP请求进行编码,但是当我发布时,我尝试放入体内的所有内容都显示为键。
代码:
var request = URLRequest(url: url)
let body = [
"email": "[email protected]",
"password": "123456"
]
let bodyData = try? JSONSerialization.data(
withJSONObject: body, options: []
)
request.httpMethod = "POST"
request.httpBody = bodyData
当我将其发布到服务器上时,服务器会收到:
{
"{\"email\":\"[email protected]\",\"password\":\"123456\"}": ""
}
我是一个迅速的初学者,非常感谢对此的任何响应...
I am trying to encode key/value pairs in JSON for an HTTP request in Swift on iOS 15, but everything I try to put in the body shows up as the key when I post it.
The code:
var request = URLRequest(url: url)
let body = [
"email": "[email protected]",
"password": "123456"
]
let bodyData = try? JSONSerialization.data(
withJSONObject: body, options: []
)
request.httpMethod = "POST"
request.httpBody = bodyData
When I post this to the server, the server receives:
{
"{\"email\":\"[email protected]\",\"password\":\"123456\"}": ""
}
Am a Swift beginner, many thanks for any responses to this...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请求
尝试将其添加到我遇到同样问题时为我解决的 。这告诉服务器将JSON解析为JSON,而不是
{JSONBODY:“”},
这似乎是现在正在做的事情。
Try adding this to the request
That is what solved it for me when I had the same problem. This tells the server to parse the json as json instead of
{ jsonBody : "" }
which is what it seems to be doing right now.