0

问题:尝试使用包含动态对象名称的 JSON 有效负载。由于这些对象的名称不是连续的或源自模式,因此我无法使用 SwiftyJSON 遍历有效负载。动态对象的示例如下所示,以粗体表示:

“180A”:{“id”:“180A”,“标签”:“海滨之门”,“路径”:“北”,“索引”:“1”}, “195C”:{“id”:“195C” ", "label": "Dune Beach Gate", "path": "North", "index": "2" }, "211F" : { "id": "211F", "label": "日落港门", "路径": "北", "索引": "3" }

示例 JSON 有效负载:

{
"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)")
    }
4

1 回答 1

2

这是解决方案:

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
        }
    }
于 2015-01-18T16:17:36.153 回答