title: Rest json POST error Handling in Swift 2
body: <p>An new to swift 2 and I try to write an App in Swift 2 that makes an HTTP POST request but I can't figure out how to use the new error handling of Swift 2.am using do try catch method but still error shows 
  "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write"</p>
  
  <p>here is the code works in swift 1.2</p>
  
  <pre><code>//Post request to json
      var request = NSMutableURLRequest(URL: NSURL(string: url)!)
      var session = NSURLSession.sharedSession()
      request.HTTPMethod = "POST"
  
      var jsonString = "{\"Authentication\":{\"Username\":\"test\",\"Password\":\"test\"},\"RequestType\":4}"
      var err: NSError?
      request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
      request.addValue("application/json", forHTTPHeaderField: "Content-Type")
      request.addValue("application/json", forHTTPHeaderField: "Accept")
      var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -&gt; Void in
          //println("Response: \(response)")
          var strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
          print("Body: \(strData)")
          var err: NSError?
          var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &amp;err) as? NSDictionary
          // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
          if(err != nil) {
              println(err!.localizedDescription)
              let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
              println("Error could not parse JSON: '\(jsonStr)'")
              //postCompleted(succeeded: false, msg: "Error")
          }
          else {
              // The JSONObjectWithData constructor didn't return an error. But, we should still
              // check and make sure that json has a value using optional binding.
              if let parseJSON = json {
                  // Okay, the parsedJSON is here, let's get the value for 'success' out of it
  
                  let success = parseJSON["StatusCode"]as? Int
  
                  if(success == 200) {
  
                     println("success")
                  }
                  return
              }
              else {
                  //                    // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                  let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                  println("Error could not parse JSON: \(jsonStr)")
                  self.loadingIndicator.stopAnimating()
              }
          }
      })
      task.resume()
  </code></pre>
  
  <p>And am trying the below code in swift 2</p>
  
  <pre><code>     //Post request to json
          let request = NSMutableURLRequest(URL: NSURL(string: url)!)
          let session = NSURLSession.sharedSession()
          let jsonString : NSString = "{\"Authentication\":{\"Username\":\"\(usernameTextField.text)\",\"Password\":\"\(passwordTextField.text)\"},\"RequestType\":7}"
          request.HTTPMethod = "POST"
  
          //request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
          request.addValue("application/json", forHTTPHeaderField: "Content-Type")
          request.addValue("application/json", forHTTPHeaderField: "Accept")
  
  
          do {
              let param = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
              request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param!, options: [])
          } catch {
              print(error)
              request.HTTPBody = nil
          }
  
  
              let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -&gt; Void in
                  // handle error
                  guard error == nil
                      else
                  {
                      return
                  }
                  print("Response: \(response)")
                  let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
                  print("Body: \(strData)")
                  let json: NSDictionary?
                  do {
                      json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
                  } catch let dataError {
                      // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
                      print(dataError)
                      let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                      print("Error could not parse JSON: '\(jsonStr)'")
                      // return or throw?
                      return
                  }
  
  
                  // The JSONObjectWithData constructor didn't return an error. But, we should still
                  // check and make sure that json has a value using optional binding.
                  if let parseJSON = json {
                      // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                      let success = parseJSON["success"] as? Int
                      print("Succes: \(success)")
                  }
                  else {
                      // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                      let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                      print("Error could not parse JSON: \(jsonStr)")
                  }
  
              })
  
              task.resume()
  </code></pre>