HTTP Post Request API-解析用单引号引起来的JSON

时间:2019-01-28 15:56:22

标签: json swift dictionary encoding json-serialization

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

  

'{“ api_key”:“ key_api1234”,“ api_secret”:“ asdfg”,“ uniqueid”:“ LDM23564GQQP”,“密码”:“ 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错误

2 个答案:

答案 0 :(得分:0)

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

问题已解决:

<QuerySet [<Course: 5 test>, <Course: 9 Latex>, <Course: 5 test>]> 

答案 1 :(得分:0)

那是一个糟糕的设计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"}'