在什么情况下JSONSerialization.data(withJSONObject :)会抛出一个捕获错误?

Pau*_*ell 10 cocoa json ios swift

JSONSerialization.data(withJSONObject:options:)(dataWithJSONObject在Swift 2中也称为)throws.但是,传递无效对象会导致崩溃,而不是可捕获的错误:

do  {
    // Crash
    try JSONSerialization.data(
        withJSONObject: NSObject(),
        options: [])
    }
catch
    {
    // Never reached
    print("Caught error:", error)
    }
Run Code Online (Sandbox Code Playgroud)

为什么那个方法被宣布为"抛出"呢?在什么情况下会抛出异常?

不知道导致错误的原因使得很难知道如何处理错误,并且无法编写验证处理错误的测试.

Pau*_*ell 7

事实证明它与这个问题的情况相同:你可以创建一个包含无效unicode(什么?!)的Swift字符串,这会导致异常.

let bogusStr = String(
    bytes: [0xD8, 0x00] as [UInt8],
    encoding: String.Encoding.utf16BigEndian)!

do  {
    let rawBody = try JSONSerialization.data(
        withJSONObject: ["foo": bogusStr], options: [])
    }
catch
    {
    // Exception lands us here
    print("Caught error:", error)
    }
Run Code Online (Sandbox Code Playgroud)

为什么原始问题中的示例代码会崩溃,而不是抛出错误?

在回答一个bug报告,苹果公司通知我说,你应该打电话JSONSerialization.isValidJSONObject(_:)前data(withJSONObject:),如果你不能肯定该对象是可编码做,不能做的是API的误用,这就是为什么他们决定应该崩溃,而不是抛出一些可以捕获的东西.

  • 这并没有回答“在什么情况下 JSONSerialization 会抛出错误”的问题。我会扩展这个问题并询问“JSONSerialization 抛出什么错误”。到目前为止,我还没有在类文档中的任何地方看到这一点。 (3认同)