HTTP后请求API-解析单引号中的JSON



我的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"}'

在字符串中插入单引号并将其转换为Data。

解决问题:

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")
request.addValue("*/*", forHTTPHeaderField: "Accept")
let jsonData = "'{"api_secret":"asdfg","uniqueid":"LDM23564GQQP","pin":"94729","password":"test1","api_key":"key_api1234"}'".data(using: .utf8)
request.httpBody = jsonData
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()

最新更新