13

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)


    print(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?

lewis
  • 2,936
  • 2
  • 37
  • 72
Neil Billingham
  • 2,235
  • 4
  • 23
  • 34

1 Answers1

29

Create a String from Data and it's good practice to handle the error

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)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • 1
    ... and use that string for debugging purposes and nothing else. – gnasher729 Jul 04 '15 at 11:48
  • 1
    In Swift 2, var error : NSError? if let data = NSJSONSerialization.dataWithJSONObject(message, options: nil, error: &error) => is wrong with error: "Extra agrument 'error' in call". How you fix? – AmyNguyen Apr 27 '16 at 04:02
  • I'm not goint to catch and crash directly if the message is nil. should have check the message as? [String: Any] before doing serialization. – Anthonius Dec 07 '20 at 15:30
  • The object from which to generate JSON data. Must not be nil. Reference: https://developer.apple.com/documentation/foundation/jsonserialization/1413636-data – Anthonius Dec 07 '20 at 15:33