【问题标题】:Can't Extract Array from JSON无法从 JSON 中提取数组
【发布时间】:2016-03-30 12:53:45
【问题描述】:

我正在尝试解析来自我的服务器的 JSON 格式的响应。

这是我的代码的第一部分:

// (responseBody is of type NSData)
guard let dictionary = try? NSJSONSerialization.JSONObjectWithData(responseBody!, options: [.MutableContainers]) else{
    fatalError("JSON Root Dictionary Not Found")
}

print("Dictionary: \(dictionary)")

...日志正确给出:

Dictionary: {
    count = 1;
    date = "2015-12-22T13:16:17.727";
    items =     (
                {
            attribute1 = null;
            attribute2 = null;
            attribute3 = null;
            date = "2015-12-22T17:30:52.764";
            size = 9175;
            version = 19;
        }
    );
}

(省略不相关的字段,更改相关字段名称和值以确保机密性)

...所以键 items 的值似乎是一个符合“字典数组,每个字典都有 String 类型的键和 Any 类型的值”的对象。

接下来,继续获取items数组:

guard let count = dictionary["count"] as? Int else {
    fatalError("Item Count Not Found")
}

guard count > 0 else {
    fatalError("Item Count Is Zero")
}

guard let items = dictionary["items"]! else{
    fatalError("Items Array Not Found")
}

if items is Array<Any> { 
    // THIS TEST FAILS (SHOULD PASS?)
    print("Items is an array")
}
else if items is Dictionary<String, Any> {
    // THIS TEST FAILS, TOO (JUST OUT OF DESPERATION...)
    print("Items is a dictionary")
}
else{
    // ...SO THIS CODE RUNS.
    print("Really? \(items)")
}

但是 - 正如上面代码中的 cmets 解释的那样 - 我无法将其转换为数组,而是执行最后一个 print() 调用 (print("Really? \(items)")),给出:

Really? (
        {
        attribute1 = null;
        attribute2 = null;
        attribute3 = null;
        date = "2015-12-22T17:30:52.764";
        size = 9175;
        version = 19;
    }
)

...那么,items 的类型是什么,如何获取我的数组?

也许我遗漏了一些关于 Swift 的集合类型的东西?


注意:起初我怀疑数组元素被括在圆括号 (()) 而不是方括号 ([]) 中。但是,字典和数组的控制台输出似乎遵循这种格式,如 the answers to this question 中所述。


更新:根据@Paulw11 在下面的 cmets 中给出的提示,我通过使用以下代码解决了这个问题:

guard let items = dictionary["items"]! as? NSMutableArray else{
    fatalError("Items Array Not Found")
}

for element in documents {               // I wish I could combine these                 
    let item = element as! NSDictionary  // two lines into one (enumeration and cast)

    print("Item: \(item)")
}

...但是,我仍然不清楚如何实现不依赖 Foundation 类的纯 Swift 解决方案。


更新 2:我正在尝试使用以下代码将 NSMutableArray 转换为原生 Swift 数组:

if var nativeItems = items as? [[String: AnyObject]] {

}

但这给了我:

警告:从 'NSMutableArray' 转换为不相关的类型 '[[String : AnyObject]]' 总是失败

if 块的位置,并且(等待它):

错误:调用可以抛出,但它没有标有“尝试”和错误 未处理。

...在 AppDelegate.swift(CoreData 样板)中,完全相同的症状 described here

CoreData 代码一直在编译。如果我注释掉 if var nativeItems = items... 演员表,错误就会消失。更改变量名称无效。确实。巫毒教。

幸运的是,我可以通过扩展样板文件的 lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {... 部分中的 catch 子句来解决这个问题:

catch let error as NSError {
        // Report any error we got.

        print("Error: \(error)")

        var dict = [String: AnyObject]()

        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"

        dict[NSLocalizedFailureReasonErrorKey] = failureReason

        dict[NSUnderlyingErrorKey] = error as NSError

        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)

        // TODO: Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and 
        // terminate. You should not use this function in a shipping 
        // application, although it may be useful during development.

        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")

        abort()
    }

    return coordinator
}() 

到这里:

catch let error as NSError {
        // Report any error we got.

        print("Error: \(error)")

        var dict = [String: AnyObject]()

        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"

        dict[NSLocalizedFailureReasonErrorKey] = failureReason

        dict[NSUnderlyingErrorKey] = error as NSError

        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)

        // TODO: Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and 
        // terminate. You should not use this function in a shipping 
        // application, although it may be useful during development.

        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")

        abort()
    }
    catch {
        // << ADDED THIS "CATCH-ALL" >>
        fatalError()
    }

    return coordinator
}() 

...令人惊讶的是,上面的警告(“强制转换总是失败”)是毫无根据的,代码执行完美...

说真的,苹果?

【问题讨论】:

  • 如果你写这样的东西会发生什么:var itemsA = items as! Array&lt;Any&gt; 看看投射是否有帮助?
  • 它与Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0(在模拟器上)在同一行崩溃。
  • 设置断点并在调试器中检查items。它是什么?我的猜测是 NSArray
  • 关闭,NSMutableArray。愚蠢的我,我之前没有尝试过。使用原生 Swift 集合类型处理 JSON 的正确方法是什么?
  • 哦,是的,我没有注意到可变容器选项。由于您正在测试该类,因此您需要使用它实际上是 的类。 NSMutableArray 是一个 swift 数组,您可以使用 Swift 数组操作,但在测试变量的类型时,它实际上并不是一个 swift 数组。

标签: ios json swift nsjsonserialization


【解决方案1】:

正如您已经发现的那样,它返回 NSMutableArrayNSMutableDictionary。将其转换为 Swift 中的字典数组:

if var items = items as? [[String: AnyObject]] {
    print(items[0])
} else {
    print("Really?")
}

这就是我更喜欢 SwiftyJSON 而不是 NSJSONSerializer 的原因。

您看到的if var 可能比if let 少很多。 if var 用于保持数组可变,因为您指定了 MutableContainers 选项。

【讨论】:

  • 谢谢。实际上,我不需要 mutable 选项,但无法确定传递给 options: 的默认参数(nil 不会编译)。
  • 使用空集:options: []
  • 我收到编译器警告Cast from 'NSMutableArray' to unrelated type '[[String : AnyObject]]' always fails
  • 您是否像我的回答一样在if 语句中使用了它?如果没有,你必须使用强制向下转换as!
  • 是的,同样的 if 块。它确实在运行时工作 (???!!!!)。有关更多信息,请参阅我的更新。
【解决方案2】:
let itemsArray:NSMutableArray = NSMutableArray()

itemsArray = dictionary["items"]

print(itemsArray)

像这样试试..

【讨论】:

  • 我不需要从NSMutableArray移动到NSArray;我需要一个(本地的、非基金会的)Swift Array
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-30
  • 2019-11-21
  • 2015-04-22
  • 2017-01-07
  • 1970-01-01
  • 2019-04-21
相关资源
最近更新 更多