【发布时间】:2018-10-24 18:01:14
【问题描述】:
[注意:为了清楚起见,已对其进行了编辑,因为对于我想要的内容似乎有些混乱。我只想要原始 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
【问题讨论】:
-
可以发一些截图或者代码吗?
标签: ios json swift nsurlsession