ios - 如何在 Swift 3.1 中从 jsonObject 获取 JSONArray

标签 ios xcode swift3

{
"status": true,
"status_code": 1,
"content": [
    {
        "cat_id": "3",
        "cat_name": "Food",
        "cat_parentid": "2"
    },
    {
        "cat_id": "4",
        "cat_name": "Entertainment",
        "cat_parentid": "2"
    },
    {
        "cat_id": "5",
        "cat_name": "Cars",
        "cat_parentid": "2"
    },
    {
        "cat_id": "12",
        "cat_name": "Personal Care",
        "cat_parentid": "2"
    }
],
"message": "Success"
}

更新

do {
        //create json object from data
        if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
            completion((json as? AnyObject)!) //here completion callback will return the jsonObject to my UIViewController.
        }

    } catch let error {
        print(error.localizedDescription)
    }

这是我的 JSONObject。我对 swift 很陌生。如何快速获取内容 JSONArray 和进一步处理。?任何人都可以帮助我吗?帮助将不胜感激。

最佳答案

此代码检查状态是否为 true,获取键 content 的数组并打印数组中的所有值。

数组显然是 [[String:String]] 所以将对象转换为这个特定类型。

do {
    //create json object from data
    if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
        if let status = json["status"] as? Bool, status == true {
            if let content = json["content"] as? [[String:String]] {
                for category in content {
                    let id = category["cat_id"]
                    let name =  category["cat_name"]
                    let parentId =  category["cat_parentid"]
                    print(id , name, parentId)
                }
            }
        }
    }

} catch let error {
    print(error.localizedDescription)
}

PS:一如既往,永远不要在 Swift 中使用 .mutableContainers。没有意义

关于ios - 如何在 Swift 3.1 中从 jsonObject 获取 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45137469/

相关文章:

ios - 删除不必要的 JSON 空格

ios - 替换NSDictionary中的键值

ios - 将 Dictionary 转换为 Json 以在 Alamofire 中传递参数

ios - 如何定义水平线的起点终点

ios - NSURLSessionDataTask 与 NSURLSessionDownloadTask 之间有什么区别

ios - 将数据从 Sqlite 移动到 Swift 中的核心数据

ios - 使用 firebase 生成下载链接

ios - 使用 if else 条件语句在 Xcode/swift 中显示特定的 View Controller

iphone - iOS GameCenter 匹配器不工作

ios - swift 中的动画 : Circular Dashed Loading Bar?