【发布时间】:2016-09-20 13:54:00
【问题描述】:
我刚刚将我的项目从 Swift 2.2 转换为 3.0,并且在我的测试中抛出了一个新异常。我的一个测试中有一些 Objective C 代码,它从文件中读取一些 JSON:
+ (NSDictionary *)getJSONDictionaryFromFile:(NSString *)filename {
/* some code which checks the parameter and gets a string of JSON from a file.
* I've checked in the debugger, and jsonString is properly populated. */
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
return jsonDict;
}
我从一些 Swift 代码中调用它:
let expectedResponseJSON = BZTestCase.getJSONDictionary(fromFile: responseFileName)
这大部分在大多数情况下都可以正常工作,但我有一个导致错误的JSON 文件:
failed: caught "NSInvalidArgumentException", "-[__NSSingleObjectArrayI enumerateKeysAndObjectsUsingBlock:]: unrecognized selector sent to instance 0x608000201fa0"
奇怪的是,错误是在getJSONDictionaryFromFile方法返回之后,在Swift代码中expectedResponseJSON被填充之前产生的。对我来说,这似乎是从NSDictionary 到Dictionary 的转换,这就是问题所在。有问题的 JSON 文件是这个:
[
{
"status": "403",
"title": "Authentication Failed",
"userData": {},
"ipRangeError": {
"libraryName": "Name goes here",
"libraryId": 657,
"requestIp": "127.0.0.1"
}
}
]
如果我删除最外层的[],这个错误就会消失。我不能是唯一一个在 Swift 3 中使用数组作为 JSON 文件的顶级实体的人,我做错了什么吗?我可以做些什么来解决这个错误?
【问题讨论】:
-
当然可以使用数组作为顶级JSON对象。但是你必须把它当作一个数组,而不是一个字典。
标签: objective-c json swift3 nsdictionary