In a simple project I'm working on, I am attempting to get JSON data from a url and print it out. However it seems Swift doesnt like JSON wrapped in [] even though its valid JSON.
Here is my Swift code thats getting/parsing the 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)
}
Here is a sample of JSON that works
{
"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"
}
And a sample that causes the app to crash.
[
{
"artist": "Led Zeppelin",
"requestname": "test",
"title": "Stairway To Heaven"
},
{
"artist": "Modest Mouse",
"requestname": "test",
"title": "Lampshades On Fire"
}
]