简体   繁体   English

如何在Swift 3.1中从jsonObject获取JSONArray

[英]how to get the JSONArray from jsonObject in Swift 3.1

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

UPDATE 更新

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

this is my JSONObject. 这是我的JSONObject。 I am very new to the swift. 我是新手。 how to get the content JSONArray and further process in swift.? 如何获取内容JSONArray并迅速进行进一步处理? Anybody can help me? 有人可以帮助我吗? Help will be appreciated. 帮助将不胜感激。

This code checks if the status is true , gets the array for key content and prints all values in the array. 此代码检查状态是否为true ,获取键content的数组并打印数组中的所有值。

The array is clearly [[String:String]] so cast the object to this specific type. 数组显然是[[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: As always, never use .mutableContainers in Swift. PS:和往常一样,从不在Swift中使用.mutableContainers It's meaningless 没有意义了

Check whether your json has content array 检查您的json是否具有内容数组

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

you can extract you data by providing key 您可以通过提供密钥来提取数据

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

Then you can get json of single object for parsing by 然后您可以通过以下方法获取单个对象的json进行解析

for var cat in content
{
    print(cat) 
}

Another alternative way, by using the library. 另一种替代方法,通过使用库。

First, import JSON library for Swift - SwiftyJSON and use the code: 首先,为Swift导入JSON库-SwiftyJSON并使用代码:

import SwiftyJSON

let json = JSON(<jsonObject data>)

let contentArray: Array<JSON> = json["content"].arrayValue

Library Integration 图书馆整合
If you're using cocoapods then use this pod: 如果您使用的是椰子,请使用以下吊舱:

pod 'SwiftyJSON'

OR else just drag SwiftyJSON.swift to the project tree. 否则,只需将SwiftyJSON.swift拖到项目树即可。

You can access like below 您可以如下访问

    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 {

         }
    }

Get content array like this: 获取这样的内容数组:

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

Full sample: 完整样本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM