2014-07-18 45 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()