gpt4 book ai didi

ios - SwiftyJSON - 解析时如何循环子节点

转载 作者:行者123 更新时间:2023-11-30 13:41:56 30 4
gpt4 key购买 nike

我尝试使用 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()
}

我知道我需要循环遍历各部分以检索所有值,但我不知道如何操作。

编辑:尝试使用以下命令来执行此操作允许我访问所有部分节点;但随后“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)
}
}
}

最佳答案

一种方法可能是这样的。

编辑:我让这段代码在 Playground 上工作。

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

关于ios - SwiftyJSON - 解析时如何循环子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35465069/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com