ios - 如何从 API 调用中获取原始 JSON

标签 ios json swift nsurlsession

[注意:为了清晰起见,已经对本文进行了编辑,因为我想要的似乎有些困惑。我想要原始 JSON。在这种情况下,它应该是 {"foo":"bar"}。重要的是要强调我想要它作为一个字符串!我不需要将它解码为 Swift 对象或以任何方式编码或修改!]

是否可以从 API 调用中获取原始 JSON?目前我正在使用 URLSession.dataTask(with:request) 但响应数据包括响应 header 和正文。我只想要返回给我的原始 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))")
}

关于ios - 如何从 API 调用中获取原始 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50341111/

相关文章:

json - Wiremock:如何匹配不具有特定属性的 JSON 请求?

javascript - 如何使用 jQuery 解析 JSON

json - Play2.2 Scala 中通用案例类与 JSON 之间的自动序列化/反序列化

iOS 向后兼容性 - 一个不存在的类的分配/初始化

ios - 使用我的 swift 4 应用程序将 json 数组保存在 firebase 中

ios - 带有 TextKit 的 UITextView 中的动画 UIImage

ios - wifi不存在时NEHotspotConfigurationManager报错问题

ios - 从应用程序中删除 .mov 文件

ios - Swift AVFoundation 翻转相机功能不起作用

swift - 如何在 Xcode 中使用 Apple 的 swift-format?