[注意:对此内容进行了编辑,以使内容更加清晰,因为我想要的内容似乎有些混乱。我只想要原始JSON。在这种情况下,它应该是{"foo":"bar"}。重要的是要突出显示我希望将其作为字符串!我不需要将其解码为Swift对象或以任何方式封送或修改!]

是否可以从API调用获取原始JSON?目前,我正在使用URLSession.dataTask(with:request),但响应数据包括响应标头以及正文。我只希望原始JSON以字符串形式返回给我。

这是我正在使用的代码:

// Build the URL
var urlComponents = URLComponents()
urlComponents.scheme = "http"
urlComponents.host = "127.0.0.1"
urlComponents.port = 80
urlComponents.queryItems = [URLQueryItem(name: "foo", value: "bar")]
guard let url = urlComponents.url else {
    fatalError("Could not create URL from components")
}

// Configure the request
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = URLSession.shared.dataTask(with: request) {(responseData, response, error) in
    DispatchQueue.main.async {
        guard error == nil else {
            print("ERROR: \(String(describing: error))")
            return
        }

        guard let _ = response else {
            print("Data was not retrieved from request")
            return
        }

        print("JSON String: \(String(describing: String(data: responseData!, encoding: .utf8)))")

        if let resData = responseData {
            let jsonResponse = try? JSONSerialization.jsonObject(with: resData, options: [])

            if let response = jsonResponse as? [String: Any] {
                print("RESPONSE:")
                dump(response)
            } else {
                print("SOMETHING WENT WRONG")
            }
        }
    }
}

task.resume()

这将在控制台中产生以下内容:
JSON String: Optional("HTTP/1.1 OK\nContent-Type: application/json\n\n{\"foo\":\"bar\"}")
SOMETHING WENT WRONG

最佳答案

您将在完成处理程序Data参数中找到响应主体。您决定要使用它做什么。

let task = session.dataTask(with: request) { (responseData, response, responseError) in
    guard responseData = responseData else { return }
    print("JSON String: \(String(data: responseData, encoding: .utf8))")
}

09-25 17:20