gpt4 book ai didi

json - HTTP Post 请求 API - 解析用单引号括起来的 JSON

转载 作者:行者123 更新时间:2023-11-30 10:51:37 27 4
gpt4 key购买 nike

我的 API 仅接受单引号包装的 JSON。喜欢:

'{"api_key":"key_api1234","api_secret":"asdfg","uniqueid":"LDM23564GQQP","password":"test1","pin":"94729"}'

我在这里或互联网上都找不到明确的答案。

我尝试了对 JSON 的许多语法更改。

let parameters = ["api_key": "key_api1234",
"api_secret": "asdfg",
"uniqueid": "LDM23564GQQP",
"password": "test1",
"pin": "94729"]

guard let url = URL(string: "https://dev-api.authenticateuser") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody

let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}

if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}

}.resume()

我收到 500 错误

最佳答案

这是一个糟糕的 API 设计。强制将 JSON 嵌入到单引号中,如果您无法告诉后端开发人员修复它,我建议您这样做。

不过,如果您希望它起作用,您只需将单引号转换为Data,然后将您所谓的httpBody,在前后附加该单引号即可。

强制解包的做法不好(使用 !),但要强调逻辑:

let parameters = ["api_key": "key_api1234",
"api_secret": "asdfg",
"uniqueid": "LDM23564GQQP",
"password": "test1",
"pin": "94729"]

var request = URLRequest(url: URL(string: "www.stackoverflow.com")!)

let singleQuote = "'".data(using: .utf8)!
let parametersJSON = try! JSONSerialization.data(withJSONObject: parameters, options: [])

let finalBody = singleQuote + parametersJSON + singleQuote
print("request.httpBody string: \(String(data: finalBody, encoding: .utf8)!)")
request.httpBody = finalBody

输出:

$>request.httpBody string: '{"api_key":"key_api1234","uniqueid":"LDM23564GQQP","pin":"94729","password":"test1","api_secret":"asdfg"}'

关于json - HTTP Post 请求 API - 解析用单引号括起来的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54405757/

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