【问题标题】:how to get the JSONArray from jsonObject in Swift 3.1如何在 Swift 3.1 中从 jsonObject 获取 JSONArray
【发布时间】:2017-07-17 06:38:17
【问题描述】:
{
"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。我对斯威夫特很陌生。如何快速获取内容 JSONArray 和进一步处理。?任何人都可以帮助我吗?帮助将不胜感激。

【问题讨论】:

  • 你序列化了吗?
  • 在 iOS 中,您可以使用序列化将您的 JSON 转换为字典,然后解析您的数据
  • 是的。我把它序列化了。我更新了我的问题。你现在可以检查了。
  • 让 number = result?.object(forKey: "status") as! Bool if number == true { let dataArr = result?.object(forKey: "content") as! NSArray }

标签: ios xcode swift3


【解决方案1】:

此代码检查状态是否为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。没意义

【讨论】:

  • 你能解释一下为什么不使用 .mutableContainers 吗?请分享任何链接
  • 在 Swift 中,集合类型默认是可变的,使用 var 关键字。无论如何,将.mutableContainers 分配给一个常量(let)是没有用的。请看stackoverflow.com/questions/40057854/…
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    像这样获取内容数组:

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

    【讨论】:

      【解决方案4】:
      let content = dict.objectForKey("content")! as NSArray
      

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

      for var cat in content
      {
          print(cat) 
      }
      

      【讨论】:

        【解决方案5】:

        另一种方法是使用库。

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

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

        图书馆整合
        如果您使用的是 cocoapods,请使用此 pod:

        pod 'SwiftyJSON'

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

        【讨论】:

          【解决方案6】:

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

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

          【讨论】:

          • 它只检查 nil。它将打印为可选而不是数组
          • array 肯定比Array&lt;AnyObject&gt; 更具体
          • 是的,你可以提供一些特定的类型,?,great+1 @vadian
          【解决方案7】:

          你可以像下面这样访问

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-11-29
            相关资源
            最近更新 更多