如何在 Swift 中的 NSJSONSerialization.dataWithJSONObject 之后获取可读的 JSON

Posted

技术标签:

【中文标题】如何在 Swift 中的 NSJSONSerialization.dataWithJSONObject 之后获取可读的 JSON【英文标题】:How to get readable JSON after NSJSONSerialization.dataWithJSONObject in Swift 【发布时间】:2015-07-04 11:19:28 【问题描述】:

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

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,以便我可以将其复制/粘贴到 fiddler/curl 中,以帮助在服务器端诊断我的 API。上面的println(data) 行给了我十六进制数据。有什么想法吗?

【问题讨论】:

【参考方案1】:

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)

【讨论】:

... 并将该字符串用于调试目的,仅此而已。 在 Swift 2 中,var 错误:NSError? if let data = NSJSONSerialization.dataWithJSONObject(message, options: nil, error: &error) => 错误:“Extra agrument 'error' in call”。你是怎么解决的? 如果消息为零,我不会直接捕获并崩溃。应该检查消息吗? [String: Any] 在进行序列化之前。 从中生成 JSON 数据的对象。不能为零。参考:developer.apple.com/documentation/foundation/jsonserialization/…

以上是关于如何在 Swift 中的 NSJSONSerialization.dataWithJSONObject 之后获取可读的 JSON的主要内容,如果未能解决你的问题,请参考以下文章