如何从 API 调用中获取原始 JSON
How to get the raw JSON from an API call
[注意:为了清楚起见,已经对本文进行了编辑,因为似乎对我想要的内容有些困惑。我只想要原始的JSON。在这种情况下,它应该是 {"foo":"bar"}
。重要的是要强调我想要这个作为字符串!我不需要将其解码为 Swift object 或以任何方式编组或修改!]
是否可以从 API 调用中获取原始 JSON?目前我正在使用 URLSession.dataTask(with:request)
,但响应数据包括响应 header 和 body。我只想要原始 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
您需要序列化响应数据以获得原始数据 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
}
}
}
您将在完成处理程序 Data
参数中找到响应正文。您决定要用它做什么。
let task = session.dataTask(with: request) { (responseData, response, responseError) in
guard responseData = responseData else { return }
print("JSON String: \(String(data: responseData, encoding: .utf8))")
}
也许我把你的问题简单化了,但看起来你只是想要像数据到字符串转换这样简单的东西。
let jsonString = String(data: responseData, encoding: .utf8)
[注意:为了清楚起见,已经对本文进行了编辑,因为似乎对我想要的内容有些困惑。我只想要原始的JSON。在这种情况下,它应该是 {"foo":"bar"}
。重要的是要强调我想要这个作为字符串!我不需要将其解码为 Swift object 或以任何方式编组或修改!]
是否可以从 API 调用中获取原始 JSON?目前我正在使用 URLSession.dataTask(with:request)
,但响应数据包括响应 header 和 body。我只想要原始 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
您需要序列化响应数据以获得原始数据 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
}
}
}
您将在完成处理程序 Data
参数中找到响应正文。您决定要用它做什么。
let task = session.dataTask(with: request) { (responseData, response, responseError) in
guard responseData = responseData else { return }
print("JSON String: \(String(data: responseData, encoding: .utf8))")
}
也许我把你的问题简单化了,但看起来你只是想要像数据到字符串转换这样简单的东西。
let jsonString = String(data: responseData, encoding: .utf8)