如何在 Swift 3.1 中从 jsonObject 获取 JSONArray


{
"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。毫无意义

检查你的 json 是否有内容数组

if let content = json["content"] as? [Dictionary<String, AnyObject>] {
print(content) // it will give you content array
}

获取如下内容数组:

let allContent = json["content"] as? [[String: Any]]

完整示例:

do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
if let allContent = json["content"] as? [[String: Any]] {
for content in allContent {
let catId = content["cat_id"] as? String
let catName = content["cat_name"] as? String
let catParentId = content["cat_parentid"] as? String
print(">> catid=" + catId!)
print(">> catName=" + catName!)
print(">> catparentID=" + catParentId!)
}
}
}
} catch let error {
print(error.localizedDescription)
}
let content = dict.objectForKey("content")! as NSArray

然后你可以得到单个对象的json进行解析

for var cat in content
{
print(cat) 
}

另一种替代方法,通过使用库。

首先,为 Swift 导入 JSON 库 - SwiftyJSON 并使用代码:

import SwiftyJSON
let json = JSON(<jsonObject data>)
let contentArray: Array<JSON> = json["content"].arrayValue

库集成
如果您使用的是cocoapods,请使用此pod:

pod 'SwiftyJSON'

或者,只需SwiftyJSON.swift拖到项目树中即可。

您可以通过提供密钥来提取数据

if let array = result["content"] as? Array<AnyObject> {
print(arry)  
}

您可以像下面这样访问

if  let filePath = Bundle.main.path(forResource: "sample", ofType: "json"), let data = FileManager().contents(atPath: filePath) {
do {
let dicRes =  try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
let contentArray = dicRes?["content"]
print("contentArray == (contentArray)")
} catch {
}
}

最新更新