gpt4 book ai didi

swift - 如何将 json 数据发送到 API swift

转载 作者:行者123 更新时间:2023-11-30 14:08:31 24 4
gpt4 key购买 nike

我的参数有问题。这是我需要发送的内容:

{
"id": "10",
"parameters": [
{
"name": "hash",
"value": "hashText"
},
{
"name": "search",
"value": "text"
}
]
}

如何为该请求设置正确的参数变量。我使用这段代码:

   var parameters = ["id": "10",
"parameters": [
"name":"hash", "value": "hash_user",
"name":"search", "value": "text"
]]

let url = NSURL(string: "http://myServerName.com/api")
var session = NSURLSession.sharedSession()

let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST" //set http method as POST

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")

...

感谢您的帮助!

编辑:

问题出在参数变量中。现在我有:

    var parameters = [
"id": "10",
"parameters": [
["name":"hash", "value": "hash_user"]
]
]

效果很好。

最佳答案

更改此行:

var parameters = ["id": "10",
"parameters": [
"name":"hash", "value": "hash_user",
"name":"search", "value": "text"
]]

对此:

var parameters = ["id": "10",
"parameters": [
["name":"hash", "value": "hash_user"],
["name":"search", "value": "text"]
]]

因此,您在参数中创建了两个字典的数组

关于swift - 如何将 json 数据发送到 API swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32045534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com