问题:尝试使用包含动态对象名称的JSON有效内容。由于这些对象的名称不是顺序的或从模式派生的,因此我无法使用SwiftyJSON遍历有效负载。动态对象的示例如下所示:粗体:
“180A”:{ “id”:“180A”, “label”:“欧申赛德门”, “路径”:“北方”, “index”:“1” }, “195C”:{ “id”:“195C”, “label”:“沙丘海滩门”, “路径”:“北方”, “index”:“2” }, “211F”:{ “id”:“211F”, “标签”:“日落海港大门”, “路径”:“北方”, “index”:“3” }
JSON Payload示例:
{
"Direction": {
"NorthGates": {
"180A": {
"id": "180A",
"label": "Oceanside Gate",
"path": "North",
"index": "1"
},
"195C": {
"id": "195C",
"label": "Dune Beach Gate",
"path": "North",
"index": "2"
},
"211F": {
"id": "211F",
"label": "Sunset Harbor Gate",
"path": "North",
"index": "3"
}
}
}
}
使用SwiftyJSON我能够成功打印已知对象的标签,例如“180A”:
DataManager.getTopAppsDataFromFileWithSuccess { (data) -> Void in
let json = JSON(data: data)
if let gateLabel = json["Direction"]["NorthGates"]["180A"]["label"].stringValue {
//output: "Oceanside Gate"
println("NSURLSession: \(gateLabel)")
}
}
由于动态对象名称不是静态的,我无法使用上面代码中的预定义对象名来定位标签值。以下尝试返回nil值:
//stringValue = nil
if let gateLabel = json["Direction"]["NorthGates"][0].stringValue {
println("NSURLSession: \(gateLabel)")
}
//stringValue = nil
if let gateLabel = json["Direction"]["NorthGates"][0]["label"].stringValue {
println("NSURLSession: \(gateLabel)")
}
答案 0 :(得分:1)
这是解决方案:
if let gates:[String: JSON] = json["Direction"]["NorthGates"].dictionaryValue {
for item in gates {
println("Dynamic Object Gate Name: \(item.0)") //Gate Name
println(item.1["label"].stringValue) //Gate Label
println(item.1["path"].stringValue) //Gate Path
println(item.1["index"].stringValue) //Gate Index
}
}