使用[]时,Swift JSON会中断

时间:2014-12-31 04:18:13

标签: ios json swift

在我正在处理的一个简单项目中,我试图从网址获取JSON数据并将其打印出来。然而,似乎Swift不喜欢[]中包含的JSON,即使它是有效的JSON。

这是我的Swift代码,用于获取/解析JSON。

func startConnection(){
    let urlName: String = "http://SOMEURL.net/jsonout.php"
    var url: NSURL = NSURL(string: urlName)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
    connection.start()
}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
    var err: NSError
    // throwing an error on the line below (can't figure out where the error message is)
    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
    println(jsonResult)
}

以下是适用的JSON示例

{   
  "Accept-Language": "en-US,en;q=0.5",
  "Host": "headers.jsontest.com",
  "Referer": "http://www.jsontest.com/",
  "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:36.0) Gecko/20100101 Firefox/36.0",
  "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}

导致应用崩溃的示例。

[
  {
      "artist": "Led Zeppelin",
      "requestname": "test",
      "title": "Stairway To Heaven"
  },
  {
      "artist": "Modest Mouse",
      "requestname": "test",
      "title": "Lampshades On Fire"
  }
]

1 个答案:

答案 0 :(得分:2)

您正在传递第二种情况下的数组,但仍然将其转换为NSDictionary

更改以下代码:

var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

var jsonResult: NSArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray