【发布时间】:2016-02-17 18:44:54
【问题描述】:
我尝试使用 SwiftyJSON 解析以下 JSON 结构,但我不知道如何循环遍历“sections”节点。我目前拥有的代码返回每个部分的第一个部分节点,但我无法访问“Section 1b / Section 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()
}
我知道我需要遍历 section 部分来检索所有值,但我不知道该怎么做。
编辑: 尝试使用以下内容允许我访问所有部分节点;但随后 '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)
}
}
}
【问题讨论】:
标签: ios json swift parsing swifty-json