我正在使用 yajl_JSON 库从 bit.ly url 缩短服务的 JSON 响应生成 NSDictionary。
JSON 响应:
{
errorCode = 0;
errorMessage = "";
results = {
"http://www.example.com/" = {
hash = 4H5keM;
shortKeywordUrl = "";
shortUrl = "http://bit.ly/4BN4qV";
userHash = 4BN4qV;
};
};
statusCode = OK;
}
澄清一下,“http://example.com”不是子“结果”。解析后,我有 3 个三嵌套的 NSDictionaries。
问题 是“http://example.com”是任意键。我想在不知道 key 的情况下访问 key 数据。具体来说,这样我就可以得到“shortUrl”的值。 如何才能有效地做到这一点?有没有办法制作这样的 keyPath:
"results.*.shortUrl"
我已经通过执行以下操作完成了它,但我认为这不是它完成的方式:
// Parse the JSON responce
NSDictionary *jsonResponce = [data yajl_JSON];
// Find the missing key
NSString *missingKey = [[[jsonResponce valueForKeyPath:@"results"] allKeys] objectAtIndex:0];
// Log the value for "shortURL"
NSLog(@"It is : %@", [[[jsonResponce objectForKey:@"results"] valueForKeyPath:missingKey] objectForKey:@"shortUrl"]);
如果我使用的是 XML,它可能很简单,这让我相信我没有正确使用 json/objective-c。
我知道在这种情况下,当我向 Bit.ly 发出请求时,可以存储“example.com”,但是...了解 future 会很好...
谢谢。
最佳答案
NSDictionary 方法 allValues
返回一个字典中的值数组,这些值与它们的键无关,并且 Key-Value Coding for NSArrays 为数组中的所有项目生成给定键值的数组。因此,您可以执行 [[jsonResponse valueForKeyPath:@"results.allValues.shortURL"] objectAtIndex:0]
来获取 shortURL。
关于iphone - 当父键未知时在嵌套的 NSDictionary 中查找对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1922759/