繁体   English   中英

如何从API调用获取原始JSON

[英]How to get the raw JSON from an API call

[ 注意:为了清晰起见,对此进行了编辑,因为对于我想要的东西似乎有些困惑。 想要原始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))")
}

也许我在简化您的问题,但这听起来像是您只是想要像数据到字符串转换那样简单的东西。

let jsonString = String(data: responseData, encoding: .utf8)

您需要序列化响应数据以获取原始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
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM