{
"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/