3

我正在使用 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 ”是任意键。我想在不知道密钥的情况下访问密钥数据。具体来说,我可以得到“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”,但是......将来很高兴知道......

谢谢。

4

2 回答 2

4

NSDictionary 方法allValues返回一个字典中的值的数组,这些值与它们的键无关,而NSArrays 的键值编码为数组中的所有项生成一个给定键值的数组。所以你可以做得到[[jsonResponse valueForKeyPath:@"results.allValues.shortURL"] objectAtIndex:0]shortURL。

于 2009-12-17T16:15:11.583 回答
3

假设你有一个 NSDictionaryresults = [jsonResponce objectForKey:@"results]这是字典的这一部分:

{
    "http://www.example.com/" = {
          hash = 4H5keM;
          shortKeywordUrl = "";
          shortUrl = "http://bit.ly/4BN4qV";
          userHash = 4BN4qV;
    };
};

您可以遍历字典中的所有键:

NSString *shortURL = null;
for (id key in results) {
    NSDictionary* resultDict = [results objectForKey:key];
    shortURL = [resultDict objectForKey:@"shortURL"];
    NSLog(@"url: %@ shortURL: %@", key, shortURL);
}

或者您可以获取字典中的所有值并取出第一个值:

NSDictionary* resultDict = [[results allValues] objectAtIndex:0];
NSString *shortURL = [resultDict objectForKey:@"shortURL"];

或者,如果您也想要长 URL,请使用allKeys

NSString *url = [[results allKeys] objectAtIndex:0]
NSDictionary* resultDict = [results objectForKey:url];
NSString *shortURL = [resultDict objectForKey:@"shortURL"];

(请注意,您实际上应该检查 allKeys 和 allValues 返回的数组的长度。)

于 2009-12-17T16:41:14.933 回答