json - HTTP 请求 GET JSON 并读取数据

标签 json swift

我在 swift 的代码中遇到了问题。我通过 httpMethod POST 向网络服务器发出请求。这个要求可以。我在数据值中得到响应和数据。数据看起来像 JSON

{"pushValues": {"devicePushGlobal":"1","devicePushNewProducts":"1","devicePushNewOffer":"1"}}

然后我将加载此响应数据以根据响应数据设置按钮。但是我没有写这段代码。有人能帮助我吗? :)

错误代码 无法使用类型为“(with: NSString)”的参数列表调用“jsonObject” //我测试了其他选项,但我总是失败 :-(

我评论代码中的错误....

let url = "https://URL.php"
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
let bodyData = "token=" + (dts)
request.httpMethod = "POST"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main) {
    (response, data, error) in

    // here i get the result of
    // {"pushValues": {"devicePushGlobal":"1","devicePushNewProducts":"1","devicePushNewOffer":"1"}}
    var str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    var names = [String]()
    // here i will get each value of pushValues to add to the array names
    do {
        if let data = str,
        // ... and here is the error code by xcode ::: ==> Cannot invoke 'jsonObject' with an argument list of type '(with: NSString)'
        // i tested with other options but i always fail :-(
        let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
        let blogs = json["pushValues"] as? [[String: Any]] {
            for blog in blogs {
                if let name = blog["devicePushGlobal"] as? String {
                    print(name)
                    names.append(name)
                }
            }
        }
    } catch {
        print("Error deserializing JSON: \(error)")
    }
    // names array is empty
    print(names)
}

谢谢你的帮助

最佳答案

您不应该使用 var str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) 将 JSON 响应解码为 NSStringJSONSerialization.jsonObject() 需要一个 Data 对象作为输入参数,所以只需安全地解包可选的 data 变量并将其用作输入参数:

if let responesData = data, let json = try JSONSerialization.jsonObject(with: responseData) 作为? [字符串:任意],让 blogs = json["pushValues"] as? [字符串:任意]

使用原生 Swift 类型的完整代码:

...
let request = URLRequest(url: URL(string: url)!)
...
URLSession.shared.dataTask(with: request, completionHandler: {
    (response, data, error) in
    var names = [String]()
    do {
        if let responseData = data, let json = try JSONSerialization.jsonObject(with: responseData) as? [String: Any], let blogs = json["pushValues"] as? [String: Any]{
            if let name = blog["devicePushGlobal"] as? Int {
                print(name)
                names.append(name)
            }
            if let newProducts = blog["devicePushNewProducts"] as? Int{}
            if let newOffers = blog["devicePushNewOffers"] as? Int{}
        }
    } catch {
        print("Error deserializing JSON: \(error)")
    }
    // names array is empty
    print(names)
}).resume()

关于json - HTTP 请求 GET JSON 并读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45240491/

相关文章:

快速 Mac 操作系统 : make trackpad reflect display size for NSTouch events

json - 如何将 jsonb 编码为 golang 中 http 响应的一部分

javascript - 带数据源的 W2UI 网格内联编辑

json - 如何使用 papa-parse-angular2

swift - replaykit 是否允许录制屏幕然后播放屏幕?

ios - 使用swift 3将来自字段的输​​入存储为变量

javascript - 如何在 jQuery 中对字符串进行 "Quote"处理?

php - 使用可能的字典从 PHP 数组创建一个 JSON 字符串

html - NSHTMLTextDocumentType 是否支持 HTML 表格?

ios - 在 Swift 中传递空闭包的优雅方式