Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/109.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用[]时,Swift JSON会中断_Ios_Json_Swift - Fatal编程技术网

Ios 使用[]时,Swift JSON会中断

Ios 使用[]时,Swift JSON会中断,ios,json,swift,Ios,Json,Swift,在我正在进行的一个简单项目中,我试图从url获取JSON数据并将其打印出来。然而,Swift似乎不喜欢[]中包装的JSON,即使它是有效的JSON 这是我获取/解析JSON的Swift代码 func startConnection(){ let urlName: String = "http://SOMEURL.net/jsonout.php" var url: NSURL = NSURL(string: urlName)! var request: NSURLReque

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

这是我获取/解析JSON的Swift代码

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"
  }
]

在第二种情况下,您传递了一个数组,但仍然将其强制转换为
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