【问题标题】:HTTP Request GET JSON and read dataHTTP 请求 GET JSON 并读取数据
【发布时间】:2025-12-21 08:25:07
【问题描述】:

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

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

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

错误代码 Cannot invoke 'jsonObject' with an argument list of type '(with: NSString)' // 我用其他选项测试过,但总是失败:-(

我在代码中注释错误....

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)
}

感谢您的帮助

【问题讨论】:

  • 删除if let data = str

标签: json swift


【解决方案1】:

您不应使用 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) as? [String: Any], let blogs = json["pushValues"] as? [String: Any]

使用原生 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()

【讨论】:

  • 我在控制台没有输出,看代码中的打印.....NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main) { (response, data, error) in var names = [String]() do { **print(data) // CONSOLE ===> Optional(93 bytes)** if let responseData = data, let json = try JSONSerialization.jsonObject(with: responseData) as? [String: Any], let blogs = json["pushValues"] as? [[String: Any]] { **print("+++") // CONSOLE ===> no output, maybe json format wrong?** for blog in blogs {
  • 请在您的问题中包含您(预期)收到的 JSON 响应,可能其格式错误。
  • {"pushValues": {"devicePushGlobal":"0","devicePushNewProducts":"0","devicePushNewOffer":"0"}}
  • 你在“pushValues”中的值是整数,相应地改变你的解析。 if let name = blog["devicePushGlobal"] as? Int
  • 好的,谢谢,但我在以下行之后进行了打印,但在控制台中看不到此 print("+++")。所以也许问题出在下面一行,因为我的 json 错误? if let responseData = data, let json = try JSONSerialization.jsonObject(with: responseData) as? [String: Any], let blogs = json["pushValues"] as? [[String: Any]] { print("+++)"