json - 快速解析 json 数组的循环

标签 json swift parsing

这是我来自服务器的 php 文件:

<?php

    $results = Array(
        Array(
            "name"      => "William",
            "location"  => "UK",
            "action"    => "Post Update"
        ),
        Array(
            "name"      => "Sammy",
            "location"  => "US",
            "action"    => "posted news"
        )
    );

    header("Content-Type: application/json");
    echo json_encode($results);
?>

这就是我尝试从 swift 中获取 json 数组的方法

let urlPath = "http://someurltophpserver"
        let url = NSURL(string: urlPath)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
            if ((error) != nil) {
                println("Error")
            } else {
                let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
                // do something with the data
            }
        })
        task.resume()

应用程序在此行崩溃 let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary 出现错误:

Could not cast value of type '__NSArrayM' (0x8c9b58) to 'NSDictionary' (0x8c9d74).

刚接触 swift 和 http 请求,所以不完全确定这意味着什么。

最佳答案

您的应用崩溃的原因是 as!。您正在尝试强制解开可选内容,因此如果在运行时失败,应用程序将崩溃。

将行更改为:

if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
{
    // Do stuff if jsonResult set with a value of type NSDictionary
}

这将阻止应用程序崩溃,但从外观上看,JSON 序列化程序返回的顶级对象将是一个 NSArray 而不是您看起来的 NSDictionary与预期不同,这可能就是应用实际上崩溃的原因。 你的代码对编译器说“让 jsonResult 等于一个肯定会是 NSDictionary 的值”。

另外,我建议下载一些数据的最简单方法是使用 NSData(contentsOfURL:url)。使用 Grand Central Dispatch 在后台队列中运行它,以避免阻塞主线程 (UI)。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

    let data = NSData(contentsOfURL: url)

    // Run any other code on the main queue. Especially any UIKit method.

    NSOperationQueue.mainQueue().addOperationWithBlock({

        // Do stuff with data
    })
}

关于json - 快速解析 json 数组的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32802972/

相关文章:

java - Android 上的新 JSONArray(String[])

javascript - 递归搜索 JSON 字符串字典,查找键值对在 "name"中的所有值

javascript - 如何读取JSON字符串[jQuery]

ios - 具有 r g b 值的 CAGradientLayer 不起作用 SWIFT

ios - 从照片中获取后,视频及其缩略图未按顺序保存

python - PyParsing 的嵌套语法行为不符合预期

java - 多次调用 AsyncTask 失败(仅发生在旧版本的 android 上)

ios - 从 ITableViewCell 失望?到 UITableViewCell 只解包 optionals

android - 如何从在android中没有名称的嵌套json中获取数据?

c# - 验证文化中的十进制数字