【发布时间】:2015-04-20 06:49:31
【问题描述】:
我正在编写一个应用程序,我需要实现的一项功能要求该应用程序从网站中提取 JSON 数据,将其存储在字典中,然后能够使用所有键并显示值。我不知道字典的结构会是什么样子,所以我希望递归遍历字典来检索所有信息。
我将 JSON 存储在我需要的网站的字典中,当我将字典变量放入 println() 语句时,它会正确显示。
I found this link 我认为这个或它的一些变体应该可以工作,但我对 swift 还是很陌生,我不确定它是如何从 Objective-c 转换为 swift 的。
我感兴趣的链接部分是这样的:
(void)enumerateJSONToFindKeys:(id)object forKeyNamed:(NSString *)keyName
{
if ([object isKindOfClass:[NSDictionary class]])
{
// If it's a dictionary, enumerate it and pass in each key value to check
[object enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
[self enumerateJSONToFindKeys:value forKeyNamed:key];
}];
}
else if ([object isKindOfClass:[NSArray class]])
{
// If it's an array, pass in the objects of the array to check
[object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self enumerateJSONToFindKeys:obj forKeyNamed:nil];
}];
}
else
{
// If we got here (i.e. it's not a dictionary or array) so its a key/value that we needed
NSLog(@"We found key %@ with value %@", keyName, object);
}
}
我不知道该怎么做,任何帮助或正确方向的指示都非常感谢。谢谢!
编辑:这是我开始的方向,但有很多错误。我试图修复它们,但运气不佳。
func enumerateJSONToFindKeys(id:AnyObject, keyName:NSString){
if id.isKindOfClass(NSDictionary)
{
AnyObject.enumerateKeysAndObjectsUsingBlock(id.key, id.value, stop:Bool())
{
self.enumerateJSONToFindKeys(id.value, forKeyNamed: keyName)
}
}
else if id.isKindOfClass(NSArray)
{
}
}
【问题讨论】:
标签: ios objective-c json swift nsdictionary