Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON in Swift

This is my code to get JSON, and it's work with this url I found on an other questions : http://binaenaleyh.net/dusor/. But, when I use it with this url : http://www.netcampus.fr/api/schools, it didn't work at all. I have an error who said : "exc_breakpoint (code=exc_i386_bpt subcode=0x0)"

Is my code wrong, or is it the JSON data ?

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    var myData:NSData = getJSON("http://www.netcampus.fr/api/schools")
    println(myData) // show me data
    var myDict:NSDictionary = parseJSON(myData)
    println(myDict)
}

func getJSON(urlToRequest: String) -> NSData{
    return NSData(contentsOfURL: NSURL(string: urlToRequest))
}

func parseJSON(inputData: NSData) -> NSDictionary{
    var error: NSError?
    var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary // error here
    return boardsDictionary
}
}
like image 461
1L30 Avatar asked Feb 22 '26 15:02

1L30


2 Answers

Your parseJSON method crashes when parsing the second JSON. NSJSONSerialization maps its contents to an array and you are expecting a dictionary:

var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary // error here
like image 89
Rafa de King Avatar answered Feb 24 '26 06:02

Rafa de King


As @reecon pointed out ,your code should be like this

//JSON Parsing
func JSONParsingSample() {

    var myData:NSData = getJSON("http://www.netcampus.fr/api/schools")
    //println(myData) // show me data
    var myDict:NSArray = parseJSON(myData)
    println(myDict)
}
func getJSON(urlToRequest: String) -> NSData{
    return NSData(contentsOfURL: NSURL(string: urlToRequest))
}

func parseJSON(inputData: NSData) -> NSArray{
    var error: NSError?
    var boardsDictionary: NSArray = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSArray 
    return boardsDictionary
}
//end
like image 27
karthikPrabhu Alagu Avatar answered Feb 24 '26 04:02

karthikPrabhu Alagu