SwiftyJSON - 解析

时间:2016-02-17 18:44:54

标签: ios json swift parsing swifty-json

我有以下JSON结构,我尝试使用SwiftyJSON进行解析,但我无法解决如何遍历"部分"节点。我目前的代码返回每个部分的第一节节点,但我无法访问"第1b节/第2b节"元件。

{
"category": [{
    "categoryId": 1,
    "categoryHeader": "Category 1",
    "sections": [{
        "section": "Section 1a title",
        "body": "Section 1a body"
    }, {
        "section": "Section 1b title",
        "body": "Section 1b body"
    }]
}, {
    "categoryId": 2,
    "categoryHeader": "Category 2",
    "sections": [{
        "section": "Section 2a title",
        "body": "Section 2a body"
    },{
        "section": "Section 2a title",
        "body": "Section 2b body"
    }]
}]

}

我的代码是:

let path: String = NSBundle.mainBundle().pathForResource("jsonFile", ofType: "json") as String!
let data = NSData(contentsOfFile: path) as NSData!

var objects = [[String: String]]()
let json = JSON(data: data)

 func parseJSON(json: JSON) {
    for category in json["category"].arrayValue {
        let categoryHeader = category["categoryHeader"].stringValue
        let section = category["sections"][0]["section"].stringValue
        let sectionBody = category["sections"][0]["body"].stringValue
        let obj = ["categoryHeader": categoryHeader, "section": section, "body": sectionBody] //, "body": body, "title": sigs]

    objects.append(obj)
    }
    tableView.reloadData()
}

我知道我需要遍历部分部分以检索所有值,但我无法解决问题。

修改 尝试使用以下操作允许我访问所有节节点;然后是' categoryHeader'输出' x'时间取决于有多少部分:

func parseJSON(json: JSON) {
    for category in json["category"].arrayValue {
        let categoryHeader = category["categoryHeader"].stringValue

        for section in category["sections"].arrayValue {
            let sectionName = section["section"].stringValue
            let body = section["body"].stringValue
            let obj = ["categoryHeader": categoryHeader, "section": sectionName, "body": body]   
    objects.append(obj)
        }
    }
}

2 个答案:

答案 0 :(得分:0)

将:

for section in category["sections"].arrayValue {
    let sectionName = section["section"].stringValue
    let body = section["body"].stringValue
}

工作?

答案 1 :(得分:0)

这样做的一种方式可能就是这样。

编辑:我在播放场地中使用此代码。

var objects = [[String: String]]()


func parseJSON(json: JSON) {

    let jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
    let json = JSON.self(jsonResults)
   // let json = JSON(data: data) // moved this line
   let count: Int? = json.dictionary?.count

   let ct = 0
   if  ct < count {
     for index in 0...count!-1 {
       for category in json["category"].arrayValue {
        let categoryHeader = category["categoryHeader"].stringValue
        let section = category["sections"][0]["section"].stringValue
        let sectionBody = category["sections"][0]["body"].stringValue
        let obj = ["categoryHeader": categoryHeader, "section": section, "body": sectionBody] //, "body": body, "title": sigs]

        objects.append(obj)
      }
   }
    tableView.reloadData()
}