How to get readable JSON after NSJSONSerialization.dataWithJSONObject in Swift

I have some code similar to this (I've simplified it here):

let text = "abc" let iosVersion = UIDevice.currentDevice().systemVersion

let message = ["Text" : text, "IosVersion" : iosVersion]

            if NSJSONSerialization.isValidJSONObject(message){

                let url = NSURL(string: "http://localhost:3000/api/someapi")

                var request = NSMutableURLRequest(URL: url!)
                var data = NSJSONSerialization.dataWithJSONObject(message, options: nil, error: nil)


                println(data)

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

                let task = session.dataTaskWithRequest(request, completionHandler: nil)

                task.resume()

This works fine, but I'd like to see the JSON in a readable format so that I can copy/paste it into fiddler/curl to help diagnose my API at the server end. The println(data) line above gives me hexadecimal data. Any ideas?

Answers


create a NSString from NSData

let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
println(dataString)

I'd further recommend to check the success of the JSON serialization

…
var error : NSError?
if let data = NSJSONSerialization.dataWithJSONObject(message, options: nil, error: &error) {
  let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
  print(dataString)

  // do other stuff on success

} else {
  print("JSON serialization failed:  \(error)")
}

Edit:

In Swift 2 the error handling has changed

do {
  let data = try NSJSONSerialization.dataWithJSONObject(message, options:[])
  let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
  print(dataString)

  // do other stuff on success

} catch {
  print("JSON serialization failed:  \(error)")
}

Update for Swift 3

do {
  let data = try JSONSerialization.data(withJSONObject:message)
  let dataString = String(data: data, encoding: .utf8)!
  print(dataString)

  // do other stuff on success

} catch {
  print("JSON serialization failed: ", error)
}

Need Your Help

How to create a sticky navigation bar that becomes fixed to the top after scrolling

javascript html css twitter-bootstrap nav

I'm attempting to make a nav bar that appears at the bottom of the viewable page when the site is first loaded, then as the user scrolls down, the nav bar scrolls up, and eventually becomes fixed t...

PHP - concatenate or directly insert variables in string

php string variables concatenation

I am wondering, What is the proper way for inserting PHP variables into a string?