如何在 Swift 中的 NSJSONSerialization.dataWithJSONObject 之后变得可读 JSON

How to get readable JSON after NSJSONSerialization.dataWithJSONObject in Swift

我有一些类似的代码(我在这里进行了简化):

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()
}

这工作正常,但我希望以可读格式查看 JSON,以便我可以 copy/paste 将其转换为 fiddler/curl 以帮助诊断我的 API 在服务器端。上面的 println(data) 行给出了十六进制数据。有什么想法吗?

Data 创建一个 String,这是处理错误

的好习惯
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)
}