ios – Swift – 如何循环使用NSDictionary - 代码日志

ios – Swift – 如何循环使用NSDictionary

嗨,我正在学习Swift,我想从JSON Api中提取数据,我的Swift代码看起来像这样。具体来说,我需要提取每一个键及其值,(例如:打印标题的值,盖等)

//Json request
var error: NSError?
var raw = NSString.stringWithString("http://example.com/MovieAPI/api/v1/movies/")
var api_url = NSURL.URLWithString(raw)
let jsonData: NSData = NSData.dataWithContentsOfURL(api_url, options: nil, error: &error)
let result = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error)
as NSDictionary
for val in result {
   for (var i=0; i < val.value.count; i++){
       //println(val.value.valueAtIndex(3)) Not Working
   }
}

我的JSON的结构是

{
  data: [
      {
        id: 2,
        title: "Hunger Games",
        cover: "http://example.com",
        genre: 2
       }
  ]
}

帮帮我!

以下是如何处理给定的JSON:

let dataArray = result["data"] as NSArray;

print("Data items count: \(dataArray.count)")

for item in dataArray { // loop through data items
    let obj = item as NSDictionary
    for (key, value) in obj {
        print("Property: \"\(key as String)\"")
    }
}

备注:

请记住,您收到被解析的对象作为NSDictionary,当您遍历字典时,接收属性的顺序可能与原始JSON中的顺序不同。

http://stackoverflow.com/questions/24764755/swift-how-to-loop-through-nsdictionary

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:ios – Swift – 如何循环使用NSDictionary