JSONObject vs JSONArray Swift

时间:2016-06-26 21:45:36

标签: json swift http nsurlsession nsurlrequest

我试图做一个PUSH HTTP请求并且我得到一个错误描述我需要提供JSON数组而不是JSONObject,我如何从我的单个对象创建一个数组,是否可以这样做?

func printdata(){
  let myJsonDict: [String:AnyObject] = [
            "action": "Websites",
            "method":"school_webpage",
            "tid":2,
            "data":["schoolId":14273],
            "type":"rpc"
        ]
  do{
      let jsonObject = try NSJSONSerialization.dataWithJSONObject(myJsonDict, options: NSJSONWritingOptions.PrettyPrinted)
            HTTPPostJSON("http://wwww.oncoursesystems.com/json.axd/direct/router", data:jsonObject ) { (response, error) -> Void in
                print(response);
            }
       }
       catch{

       }
}

func HTTPsendRequest(request: NSMutableURLRequest, callback: (String, String?) -> Void) {
   let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
       (data, response, error) -> Void in
            if (error != nil) {
                callback("", error!.localizedDescription)
            } else {
                callback(NSString(data: data!, encoding: NSUTF8StringEncoding)! as String, nil)
            }
   }

   task.resume()
}

func HTTPPostJSON(url: String,  data: NSData, callback: (String, String?) -> Void) {

   let request = NSMutableURLRequest(URL: NSURL(string: url)!)

   request.HTTPMethod = "POST"
   request.addValue("application/json",forHTTPHeaderField: "Content-Type") 
   request.addValue("application/json",forHTTPHeaderField: "Accept")
   request.HTTPBody = data
   HTTPsendRequest(request, callback: callback)
}

我的方法调用

override func viewDidLoad() {
    super.viewDidLoad()
    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.sizeToFit()
    definesPresentationContext = true
    self.tableView.tableHeaderView = searchController.searchBar
    names = HtmlController.loadData() as NSArray as! [String]
    names.removeAtIndex(0)
    clean()
    refreshController = UIRefreshControl()
    refreshController.addTarget(self, action: #selector(WebpageController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)

    self.tableView.addSubview(refreshController)
    printdata()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

1 个答案:

答案 0 :(得分:0)

你的意思是POST请求吗?

这对我有用:

func HTTPPostJSON(url: String,  data: AnyObject, callback: (String, String?) -> Void) {
   let request = NSMutableURLRequest(URL: NSURL(string: url)!)
   request.HTTPMethod = "POST"
   request.addValue("application/json", forHTTPHeaderField: "Content-Type")
   request.addValue("application/json", forHTTPHeaderField: "Accept")    
   request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(data, options: [])
   HTTPsendRequest(request, callback: callback)
}

注意方法签名,将数据作为[" String":AnyObject]传递,并处理HTTPPostJSON方法中的序列化。我认为部分错误可能与传递格式化的json有关(使用漂亮选项时)。

修改

根据您的评论,您是否更新了打印方法以满足新方法签名?它应该是:

func printdata(){
  let myJsonDict: [String:AnyObject] = [
        "action": "Websites",
        "method":"school_webpage",
        "tid":2,
        "data":["schoolId":14273],
        "type":"rpc"]

  HTTPPostJSON("http://wwww.oncoursesystems.com/json.axd/direct/router", data:myJsonDict) { 
     (response, error) -> Void in
       print(response);
  }
}