作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的 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/
我是一名优秀的程序员,十分优秀!