[注意:这是为了清晰起见而编辑的,因为似乎对我想要的东西感到困惑。我只想要原始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
答案 0 :(得分:2)
您将在完成处理程序Data
参数中找到响应正文。你决定用它做什么。
let task = session.dataTask(with: request) { (responseData, response, responseError) in
guard responseData = responseData else { return }
print("JSON String: \(String(data: responseData, encoding: .utf8))")
}
答案 1 :(得分:1)
您需要序列化响应数据以获取原始JSON:
URLSession.shared.dataTask(with: urlRequest) { (responseData, response, error) in
// check for errors, then...
if let resData = responseData {
let jsonResponse = try? JSONSerialization.jsonObject(with: resData, options: [])
if let response = jsonResponse as? [String: Any] {
// ... handle response
}
}
}
答案 2 :(得分:1)
也许我过分简化了你的问题,但它看起来就像你只是想要像数据到字符串转换一样简单。
margin-left: 1rem