2014-07-18 82 views
3

這是我的代碼來獲取JSON,它與我在其他問題上找到的這個URL一起工作:http://binaenaleyh.net/dusor/。 但是,當我使用它與此網址:http://www.netcampus.fr/api/schools,它根本沒有工作。我有一個錯誤說:「exc_breakpoint(code = exc_i386_bpt subcode = 0x0)」在Swift中獲取JSON

是我的代碼錯了,還是它的JSON數據?

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 
} 
} 
+0

乘坐齒賺取至少一一點關於JSON。有了一點JSON知識,人們可以看到一個頂級數組,另一個頂級字典。作爲軟件開發人員需要了解您編寫的代碼**和**從其他人處獲得的代碼。 – zaph

回答

6

您的parseJSON方法在解析第二個JSON時崩潰。 NSJSONSerialization其內容映射到一個數組,你期待的字典:

var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary // error here 
3

由於@reecon指出的那樣,你的代碼應該是這樣的

//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 
-1
let urlString = "webAPI" 
    var request = URLRequest(url: URL(string: urlString)!) 

    let session = URLSession.shared 
    request.httpMethod = "GET" 
    session.dataTask(with: request) 

    { 
     data, response, error in 
     if error != nil 
     { 
      print(error!.localizedDescription) 
      return 
     } 

     do 
     { 


      let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary 
      self.dict = jsonResult as! NSMutableDictionary 
      print("Synchronous\(jsonResult)") 

      DispatchQueue.main.async 
       { 

       let url = URL(string: ((((self.dict.value(forKey: "sources") as! NSArray).object(at: 5) as! NSDictionary).value(forKey: "urlsToLogos") as? NSDictionary)?.value(forKey: "small") as? String)!) 
       let data = try? Data(contentsOf: url!) 


      } 


         } 
     catch 
     { 
      print"error" 
     } 

     }.resume()