【发布时间】: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<Any>看看投射是否有帮助? -
它与
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0(在模拟器上)在同一行崩溃。 -
设置断点并在调试器中检查
items。它是什么?我的猜测是 NSArray -
关闭,
NSMutableArray。愚蠢的我,我之前没有尝试过。使用原生 Swift 集合类型处理 JSON 的正确方法是什么? -
哦,是的,我没有注意到可变容器选项。由于您正在测试该类,因此您需要使用它实际上是 的类。 NSMutableArray 是一个 swift 数组,您可以使用 Swift 数组操作,但在测试变量的类型时,它实际上并不是一个 swift 数组。
标签: ios json swift nsjsonserialization