在Swift中正确编码JSON主体以供HTTP请求

发布于 2025-02-14 01:41:48 字数 826 浏览 0 评论 0原文

我正在尝试在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

喜爱皱眉﹌ 2025-02-21 01:41:48

请求

request.setValue("application/json", forHTTPHeaderField: "Content-Type")

尝试将其添加到我遇到同样问题时为我解决的 。这告诉服务器将JSON解析为JSON,而不是

{JSONBODY:“”},

这似乎是现在正在做的事情。

Try adding this to the request

request.setValue("application/json", forHTTPHeaderField: "Content-Type")

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文